class LogOptions(unittest.TestCase): def setUp(self): self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" def test_no_log(self): self.p = Pynliner() self.assertEqual(self.p.log, None) self.assertEqual(cssutils.log.enabled, False) def test_custom_log(self): self.log = logging.getLogger('testlog') self.log.setLevel(logging.DEBUG) self.logstream = StringIO.StringIO() handler = logging.StreamHandler(self.logstream) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) self.log.addHandler(handler) self.p = Pynliner(self.log).from_string(self.html) self.p.run() log_contents = self.logstream.getvalue() self.assertIn("DEBUG", log_contents)
def process_dict(self, input_dict): converter = Ansi2HTMLConverter() full = self.arg_value('full', False) ext = self.artifact.input_ext if input_dict.has_key('1') and not input_dict['1'] and ext == ".css": # Special case if we get a virtual empty file, generate style file self.artifact.final = True self.artifact.ext = ext output_dict = OrderedDict() output_dict['1'] = self.generate_css() else: p = None css = None inline_css = self.arg_value('inline', False) if inline_css: css = "\n".join(converter.produce_headers().strip().splitlines()[1:-1]) self.log.debug(css) try: from pynliner import Pynliner except ImportError: raise UserFeedback("You must install BeautifulSoup, cssutils and pynliner in order to use 'inline' option:\n pip install BeautifulSoup cssutils pynliner\n") output_dict = OrderedDict() for section_name, section_text in input_dict.iteritems(): html = converter.convert(section_text, full=full) if inline_css: p = Pynliner(self.log).from_string(html).with_cssString(css) html = "<pre>\n%s</pre>" % p.run() output_dict[section_name] = html return output_dict
class LogOptions(unittest.TestCase): def setUp(self): self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" def test_no_log(self): self.p = Pynliner() self.assertEqual(self.p.log, None) self.assertEqual(cssutils.log.enabled, False) def test_custom_log(self): self.log = logging.getLogger('testlog') self.log.setLevel(logging.DEBUG) self.logstream = StringIO.StringIO() handler = logging.StreamHandler(self.logstream) log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" formatter = logging.Formatter(log_format) handler.setFormatter(formatter) self.log.addHandler(handler) self.p = Pynliner(self.log).from_string(self.html) self.p.run() log_contents = self.logstream.getvalue() self.assertTrue("DEBUG" in log_contents)
def ansi_output_to_html(ansi_text, log=None): try: converter = Ansi2HTMLConverter() html = converter.convert(ansi_text) except IOError as e: if re.search("templates/header.mak", str(e)): print e raise Exception( "Your installation of ansi2html is missing some template files, please try 'pip install --upgrade ansi2html' or install from source." ) raise e try: p = Pynliner(log) if not log: # put after call to Pynliner() so it doesn't print in case of error print """a custom log has not been passed to dexy.utils.ansi_output_to_html, harmless but annoying CSS errors will appear on the console.""" except TypeError: print "========== Start of harmless but annoying CSS errors..." print "You can install pynliner from source (https://github.com/rennat/pynliner.git) or version > 0.2.1 to get rid of these" p = Pynliner() p.from_string(html) html_with_css_inline = p.run() # Ansi2HTMLConverter returns a complete HTML document, we just want body doc = BeautifulSoup(html_with_css_inline) return doc.body.renderContents()
class CaseSensitive(unittest.TestCase): def setUp(self): self.pyn = Pynliner(case_sensitive=False) def test_case_sensitive_tag(self): # Test upper/lowercase tag names in style sheets html = '<style>H1 {color: #000;}</style><H1 style="color: #fff">Foo</H1><h1>Bar</h1>' desired_output = '<h1 style="color: #000; color: #fff">Foo</h1><h1 style="color: #000">Bar</h1>' output = self.pyn.from_string(html).run() self.assertEqual(output, desired_output) def test_case_sensitive_tag_class(self): # Test upper/lowercase tag names with class names html = '<style>h1.b1 { font-weight:bold; } H1.c {color: red}</style><h1 class="b1">Bold</h1><H1 class="c">Bold Red</h1>' desired_output = '<h1 class="b1" style="font-weight: bold">Bold</h1><h1 class="c" style="color: red">Bold Red</h1>' output = self.pyn.from_string(html).run() self.assertEqual(output, desired_output) def test_case_sensitive_tag_id(self): # Test case sensitivity of tags with class names html = '<style>h1#tst { font-weight:bold; } H1#c {color: red}</style><h1 id="tst">Bold</h1><H1 id="c">Bold Red</h1>' desired_output = '<h1 id="tst" style="font-weight: bold">Bold</h1><h1 id="c" style="color: red">Bold Red</h1>' output = self.pyn.from_string(html).run() self.assertEqual(output, desired_output) def test_case_sensitive_class(self): # Test case insensitivity of class names html = '<style>h1.BOLD { font-weight:bold; }</style><h1 class="bold">Bold</h1><h1 class="BOLD">Bold</h1>' desired_output = '<h1 class="bold" style="font-weight: bold">Bold</h1><h1 class="BOLD" style="font-weight: bold">Bold</h1>' output = self.pyn.from_string(html).run() self.assertEqual(output, desired_output)
def test_06_with_cssString(self): """Test 'with_cssString' method""" cssString = 'h1 {font-size: 2em;}' self.p = Pynliner().from_string(self.html).with_cssString(cssString) self.assertEqual(self.p.style_string, cssString + '\n') output = self.p.run() self.assertEqual(output, u'<h1 style="font-size: 2em; color: #fc0">Hello World!</h1>')
def test_06_with_cssString(self): """Test 'with_cssString' method""" cssString = '.b1,.b2 {font-size: 2em;}' self.p = Pynliner().from_string(self.html).with_cssString(cssString) self.assertEqual(self.p.style_string, cssString + '\n') output = self.p.run() self.assertEqual(output, u'<span class="b1" style="font-size: 2em; font-weight: bold">Bold</span><span class="b2 c" style="font-size: 2em; font-weight: bold; color: red">Bold Red</span>')
def handle(self, *args, **options): #employers = Employer.objects.visible().filter(feature_in_monthly_newsletter=True) all_events_and_deadlines = Event.objects.filter( include_in_monthly_newsletter=True) events = filter(lambda x: not x.is_deadline() and not x.is_past(), all_events_and_deadlines) deadlines = filter(lambda x: x.is_deadline(), all_events_and_deadlines) if events or deadlines: year = datetime.now().strftime("%Y") month = datetime.now().strftime("%B") for i, student in enumerate( Student.objects.filter( user__is_active=True, user__userattributes__is_verified=True, studentpreferences__receive_monthly_newsletter=True, first_name="Dmitrij")): if i % 5 == 0: time.sleep(1) context = Context({ 'first_name': student.first_name, 'student': student, #'employer':employers, 'events': events, 'deadlines': deadlines, 'month': month, 'year': year }) context.update(get_basic_email_context()) text_email_body = render_to_string("monthly_newsletter.txt", context) html_email_body = render_to_string("monthly_newsletter.html", context) html_email_body = Pynliner().from_string(html_email_body).run() subject = ''.join( render_to_string('email_subject.txt', { 'message': "%s Newsletter" % month }, context).splitlines()) send_email(subject, text_email_body, [student.user.email]) newsletter_path = "%s/newsletter/templates/%s/" % (s.ROOT, year) if not os.path.exists(newsletter_path): os.makedirs(newsletter_path) context['first_name'] = None context['student'] = None body = render_to_string("monthly_newsletter.html", context) body = Pynliner().from_string(body).run() f = open("%s%s.html" % (newsletter_path, month), "w") f.write(body) f.close()
def test_multiple_pseudo_selectors(self): html = """<h1><span>Hello World!</span></h1>""" css = """span:first-child:last-child { color: red; }""" expected = u"""<h1><span style="color: red">Hello World!</span></h1>""" output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected) html = """<h1><span>Hello World!</span><span>again!</span></h1>""" css = """span:first-child:last-child { color: red; }""" expected = u"""<h1><span>Hello World!</span><span>again!</span></h1>""" output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected)
def setUp(self): self.log = logging.getLogger('testlog') self.log.setLevel(logging.DEBUG) self.logstream = StringIO.StringIO() handler = logging.StreamHandler(self.logstream) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) self.log.addHandler(handler) self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" self.p = Pynliner(self.log).from_string(self.html)
def _test_external_url(self, url, expected_url): with mock.patch.object(Pynliner, '_get_url') as mocked: def check_url(url): self.assertEqual(url, expected_url) return ".b1,.b2 { font-weight:bold; } .c {color: red}" mocked.side_effect = check_url p = Pynliner() p.root_url = self.root_url p.relative_url = self.relative_url p.from_string(self.html_template.format(href=url)) p._get_soup() p._get_styles()
def process_dict(self, input_dict): # matches = [k for k in self.artifact.input_artifacts_dict.keys() if k.endswith(".css|dexy")] # k = matches[0] css = open("pastie.css", "r").read() output_dict = OrderedDict() for k, v in input_dict.items(): try: p = Pynliner(self.log) except TypeError: print "the pynliner filter says: please upgrade to the latest version of pynliner (e.g. easy_install -U pynliner)" p = Pynliner() p.from_string(v).with_cssString(css) output_dict[k] = p.run() return output_dict
def test_custom_log(self): self.log = logging.getLogger('testlog') self.log.setLevel(logging.DEBUG) self.logstream = StringIO.StringIO() handler = logging.StreamHandler(self.logstream) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) self.log.addHandler(handler) self.p = Pynliner(self.log).from_string(self.html) self.p.run() log_contents = self.logstream.getvalue() self.assertIn("DEBUG", log_contents)
def process_dict(self, input_dict): #matches = [k for k in self.artifact.input_artifacts_dict.keys() if k.endswith(".css|dexy")] #k = matches[0] css = open("pastie.css", "r").read() output_dict = OrderedDict() for k, v in input_dict.items(): try: p = Pynliner(self.log) except TypeError: print "the pynliner filter says: please install pynliner from source (https://github.com/rennat/pynliner.git) or version > 0.2.1" p = Pynliner() p.from_string(v).with_cssString(css) output_dict[k] = p.run() return output_dict
def email_to_html_text(msgBody): BODY_TEXT = html2text.html2text(msgBody) # The HTML body of the email. BODY_HTML = ( Pynliner().from_string(msgBody).run() ) # bleach.linkify(bleach.clean(msgBody)) return BODY_TEXT, BODY_HTML
def test_parent_pseudo_selector(self): html = """<h1><span><span>Hello World!</span></span></h1>""" css = """span:last-child span { color: red; }""" expected = u"""<h1><span><span style="color: red">Hello World!</span></span></h1>""" output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected) html = """<h1><span><span>Hello World!</span></span></h1>""" css = """span:last-child > span { color: red; }""" expected = u"""<h1><span><span style="color: red">Hello World!</span></span></h1>""" output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected) html = """<h1><span><span>Hello World!</span></span><span>nope</span></h1>""" css = """span:last-child > span { color: red; }""" expected = u"""<h1><span><span>Hello World!</span></span><span>nope</span></h1>""" output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected)
def send_activation_email(self, primary=True, password=None, custom_msg=None): if self.activation_key_expired(): self.reset_activation() if custom_msg: custom_msg = custom_msg.replace('\n', '<br>') custom_msg = mark_safe(custom_msg) ctx_dict = { 'activation_key': self.activation_key, 'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS, 'password': password, 'primary': primary, 'user': self.user, 'custom_msg': custom_msg } message = render_to_string('registration/activation_email.html', ctx_dict) message = Pynliner().from_string(message).run() site = getattr(settings, 'SITE', None) headers = { 'X-SMTPAPI': '{"category": "Activation sent (%s)"}' % self.pk } send_email(message, email_type=settings.ACTIVATION, recipients=[self.email], site=site, headers=headers)
def test_adjacent_selector(self): html = """<h1>Hello World!</h1><h2>How are you?</h2>""" css = """h1 + h2 { color: red; }""" expected = (u'<h1>Hello World!</h1>' u'<h2 style="color: red">How are you?</h2>') output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected)
def compose_preview(request): config = get_user_config(request.user) params = request.GET template_content = getParamDefault(params, "template_content", "") template_test_case = getParamDefault(params, "template_test_case", "") test_case_xform = getParamDefault(params, "test_case_xform", None) stylesheet_content = getParamDefault(params, "template_stylesheet_content", "") try: subs = getData(config, data_file=template_test_case, local_data_folder="test_data", xform_file=test_case_xform) except: subs = {} try: subs = subs["docroot"] except: pass template_content = preprocess(template_content) rendered = substituteVariablesPlainString(config, template_content, subs) rendered = convert_markdown_string(rendered) rendered = '<div class="echo-publish">' + rendered + "</div>" rendered = Pynliner().from_string(rendered).with_cssString( stylesheet_content).run() return JsonResponse({"preview": rendered})
def test_child_with_first_child_and_unmatched_class_selector_complex_dom( self): html = """<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>""" css = """h1 > .hello:first-child { color: green; }""" expected = u"""<h1><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></h1>""" output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected)
def test_nested_child_with_first_child_override_selector_complex_dom(self): self.maxDiff = None html = """<div><div><span>Hello World!</span><p>foo</p><div class="barclass"><span>baz</span>bar</div></div></div>""" css = """div > div > * { color: green; } div > div > :first-child { color: red; }""" expected = u"""<div><div><span style="color: red">Hello World!</span><p style="color: green">foo</p><div class="barclass" style="color: green"><span style="color: red">baz</span>bar</div></div></div>""" output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected)
def test_mixed_styles(self): """Test media queries do not affect regular operation""" html = '<style>' + self.mq + ' h1 {color:#ffcc00;}</style>'\ '<h1>Foo</h1><div class="infobox">Blah</div>' desired_output = '<style>' + self.mq + '</style>'\ '<h1 style="color: #fc0">Foo</h1><div class="infobox">Blah</div>' output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output)
def test_leave_alone(self): """Test media queries are 'left alone'""" html = '<style>' + self.mq + '</style>'\ '<h1>Foo</h1><div class="infobox">Blah</div>' desired_output = '<style>' + self.mq + '</style>'\ '<h1>Foo</h1><div class="infobox">Blah</div>' output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output)
def _render(self, context): """ Renders the plain and html versions of a template. Return both in a tuple, where the first element is the plain text version and the second element is the html version :return: (str, str,) """ if not context: context = Context({}) plain = self.template_plain.render(context) html = self.template_html.render(context) css = get_template(self.template_style).render(Context({})) p = Pynliner() html = p.from_string(html).with_cssString(css).run() return plain, html
class WithCustomLog(unittest.TestCase): def setUp(self): self.log = logging.getLogger('testlog') self.log.setLevel(logging.DEBUG) self.logstream = StringIO.StringIO() handler = logging.StreamHandler(self.logstream) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) self.log.addHandler(handler) self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" self.p = Pynliner(self.log).from_string(self.html) def test_custom_log(self): self.p.run() log_contents = self.logstream.getvalue() assert "DEBUG" in log_contents
def test_real_html(self): """Test re-inserted styles are placed in the body for HTML""" html = '<html><head><style>' + self.mq + ' h1 {color:#ffcc00;}</style></head>'\ '<body><h1>Foo</h1><div class="infobox">Blah</div>' desired_output = '<html><head></head><body><style>' + self.mq + '</style>'\ '<h1 style="color: #fc0">Foo</h1><div class="infobox">Blah</div>'\ '</body></html>' output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output)
def convert_markdown(fileNameIn, fileNameOut, css_string=None): fileIn = open(fileNameIn, "r", encoding="utf-8") fileOut = open(fileNameOut, "w", encoding="utf-8") html = markdown(fileIn.read()) if css_string: html = '<div class="echo-publish">' + html + "</div>" html = Pynliner().from_string(html).with_cssString(css_string).run() fileOut.write(html) fileOut.close() return {"file": fileNameOut}
class WithCustomLog(unittest.TestCase): def setUp(self): self.log = logging.getLogger('testlog') self.log.setLevel(logging.DEBUG) self.logstream = StringIO.StringIO() handler = logging.StreamHandler(self.logstream) formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) self.log.addHandler(handler) self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" self.p = Pynliner(self.log).from_string(self.html) def test_custom_log(self): self.p.run() log_contents = self.logstream.getvalue() assert "DEBUG" in log_contents
def setUp(self): self.log = logging.getLogger('testlog') self.log.setLevel(logging.DEBUG) self.logstream = StringIO.StringIO() handler = logging.StreamHandler(self.logstream) formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") handler.setFormatter(formatter) self.log.addHandler(handler) self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" self.p = Pynliner(self.log).from_string(self.html)
def email_from_template(html_template, txt_template, context, from_email): html_email = loader.render_to_string(html_template, context) html_email = Pynliner().from_string(html_email).run() text_email = loader.render_to_string(txt_template, context) details = { 'subject': context['subject'], 'body': text_email, 'from_email': from_email, 'to': context['to'], } msg = EmailMultiAlternatives(**details) msg.attach_alternative(html_email, 'text/html') return msg
class CommaSelector(unittest.TestCase): def setUp(self): self.html = """<style>.b1,.b2 { font-weight:bold; } .c {color: red}</style><span class="b1">Bold</span><span class="b2 c">Bold Red</span>""" self.p = Pynliner().from_string(self.html) def test_fromString(self): """Test 'fromString' constructor""" self.assertEqual(self.p.source_string, self.html) def test_get_soup(self): """Test '_get_soup' method""" self.p._get_soup() self.assertEqual(unicode(self.p.soup), self.html) def test_get_styles(self): """Test '_get_styles' method""" self.p._get_soup() self.p._get_styles() self.assertEqual(self.p.style_string, u'.b1,.b2 { font-weight:bold; } .c {color: red}\n') self.assertEqual(unicode(self.p.soup), u'<span class="b1">Bold</span><span class="b2 c">Bold Red</span>') def test_apply_styles(self): """Test '_apply_styles' method""" self.p._get_soup() self.p._get_styles() self.p._apply_styles() self.assertEqual(unicode(self.p.soup), u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="color: red; font-weight: bold">Bold Red</span>') def test_run(self): """Test 'run' method""" output = self.p.run() self.assertEqual(output, u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="color: red; font-weight: bold">Bold Red</span>') def test_with_cssString(self): """Test 'with_cssString' method""" cssString = '.b1,.b2 {font-size: 2em;}' self.p = Pynliner().from_string(self.html).with_cssString(cssString) output = self.p.run() self.assertEqual(output, u'<span class="b1" style="font-weight: bold; font-size: 2em">Bold</span><span class="b2 c" style="color: red; font-weight: bold; font-size: 2em">Bold Red</span>') def test_fromString_complete(self): """Test 'fromString' complete""" output = pynliner.fromString(self.html) desired = u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="color: red; font-weight: bold">Bold Red</span>' self.assertEqual(output, desired) def test_comma_whitespace(self): """Test excess whitespace in CSS""" html = '<style>h1, h2 ,h3,\nh4{ color: #000} </style><h1>1</h1><h2>2</h2><h3>3</h3><h4>4</h4>' desired_output = '<h1 style="color: #000">1</h1><h2 style="color: #000">2</h2><h3 style="color: #000">3</h3><h4 style="color: #000">4</h4>' output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output) def test_comma_separated_nested_styles(self): html = """<style>.orange-wrapper p, .super-orange-wrapper p { color:orange; }</style><div class="orange-wrapper"><p>Orange</p></div><div><p>Black</p></div>""" desired_output = """<div class="orange-wrapper"><p style="color: orange">Orange</p></div><div><p>Black</p></div>""" output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output)
def test_08_fromURL(self): """Test 'fromURL' constructor""" url = 'https://raw.github.com/voidfiles/pynliner/master/test_data/test.html' p = Pynliner() p.from_url(url) self.assertEqual(p.root_url, 'https://raw.github.com') self.assertEqual(p.relative_url, 'https://raw.github.com/voidfiles/pynliner/master/test_data/') p._get_soup() p._get_external_styles() self.assertEqual(p.style_string, "p {color: #999}") p._get_internal_styles() self.assertEqual(p.style_string, "p {color: #999}\nh1 {color: #ffcc00;}") p._get_styles() output = p.run() desired = u"""<html><head></head><body>\n <h1 style="color: #fc0">Testing Title</h1>\n <p style="color: #999">Awesome</p>\n </body></html>""" self.assertEqual(output, desired)
def test_no_log(self): self.p = Pynliner() self.assertEqual(self.p.log, None) self.assertEqual(cssutils.log.enabled, False)
def setUp(self): self.html = "<html><head><style>h1 { color:#ffcc00; }</style></head><body><h1>Hello World!</h1></body></html>" self.p = Pynliner().from_string(self.html)
def test_08_comma_whitespace(self): """Test excess whitespace in CSS""" html = '<style>h1, h2 ,h3,\nh4{ color: #000} </style><h1>1</h1><h2>2</h2><h3>3</h3><h4>4</h4>' desired_output = '<h1 style="color: #000">1</h1><h2 style="color: #000">2</h2><h3 style="color: #000">3</h3><h4 style="color: #000">4</h4>' output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output)
class CommaSelector(unittest.TestCase): def setUp(self): self.html = """<style>.b1,.b2 { font-weight:bold; } .c {color: red}</style><span class="b1">Bold</span><span class="b2 c">Bold Red</span>""" self.p = Pynliner().from_string(self.html) def test_01_fromString(self): """Test 'fromString' constructor""" self.assertEqual(self.p.source_string, self.html) def test_02_get_soup(self): """Test '_get_soup' method""" self.p._get_soup() self.assertEqual(unicode(self.p.soup), self.html) def test_03_get_styles(self): """Test '_get_styles' method""" self.p._get_soup() self.p._get_styles() self.assertEqual(self.p.style_string, u'.b1,.b2 { font-weight:bold; } .c {color: red}\n') self.assertEqual( unicode(self.p.soup), u'<span class="b1">Bold</span><span class="b2 c">Bold Red</span>') def test_04_apply_styles(self): """Test '_apply_styles' method""" self.p._get_soup() self.p._get_styles() self.p._apply_styles() self.assertEqual( unicode(self.p.soup), u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="font-weight: bold; color: red">Bold Red</span>' ) def test_05_run(self): """Test 'run' method""" output = self.p.run() self.assertEqual( output, u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="font-weight: bold; color: red">Bold Red</span>' ) def test_06_with_cssString(self): """Test 'with_cssString' method""" cssString = '.b1,.b2 {font-size: 2em;}' self.p = Pynliner().from_string(self.html).with_cssString(cssString) self.assertEqual(self.p.style_string, cssString + '\n') output = self.p.run() self.assertEqual( output, u'<span class="b1" style="font-size: 2em; font-weight: bold">Bold</span><span class="b2 c" style="font-size: 2em; font-weight: bold; color: red">Bold Red</span>' ) def test_07_fromString(self): """Test 'fromString' complete""" output = pynliner.fromString(self.html) desired = u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="font-weight: bold; color: red">Bold Red</span>' self.assertEqual(output, desired) def test_08_comma_whitespace(self): """Test excess whitespace in CSS""" html = '<style>h1, h2 ,h3,\nh4{ color: #000} </style><h1>1</h1><h2>2</h2><h3>3</h3><h4>4</h4>' desired_output = '<h1 style="color: #000">1</h1><h2 style="color: #000">2</h2><h3 style="color: #000">3</h3><h4 style="color: #000">4</h4>' output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output)
def setUp(self): self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" self.p = Pynliner().from_string(self.html)
class Basic(unittest.TestCase): def setUp(self): self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" self.p = Pynliner().from_string(self.html) def test_fromString(self): """Test 'fromString' constructor""" self.assertEqual(self.p.source_string, self.html) def test_get_soup(self): """Test '_get_soup' method""" self.p._get_soup() self.assertEqual(unicode(self.p.soup), self.html) def test_get_styles(self): """Test '_get_styles' method""" self.p._get_soup() self.p._get_styles() self.assertEqual(self.p.style_string, u'h1 { color:#ffcc00; }\n') self.assertEqual(unicode(self.p.soup), u'<h1>Hello World!</h1>') def test_apply_styles(self): """Test '_apply_styles' method""" self.p._get_soup() self.p._get_styles() self.p._apply_styles() attr_dict = dict(self.p.soup.contents[0].attrs) self.assertTrue('style' in attr_dict) self.assertEqual(attr_dict['style'], u'color: #fc0') def test_run(self): """Test 'run' method""" output = self.p.run() self.assertEqual(output, u'<h1 style="color: #fc0">Hello World!</h1>') def test_with_cssString(self): """Test 'with_cssString' method""" cssString = 'h1 {color: #f00;}' self.p.with_cssString(cssString) output = self.p.run() self.assertEqual(output, u'<h1 style="color: #f00">Hello World!</h1>') def test_fromString_complete(self): """Test 'fromString' complete""" output = pynliner.fromString(self.html) desired = u'<h1 style="color: #fc0">Hello World!</h1>' self.assertEqual(output, desired) def test_fromURL(self): """Test 'fromURL' constructor""" url = 'http://media.tannern.com/pynliner/test.html' p = Pynliner() with mock.patch.object(Pynliner, '_get_url') as mocked: mocked.return_value = u"""<?xml version='1.0' encoding='utf-8'?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test</title> <link rel="stylesheet" type="text/css" href="test.css"/> <style type="text/css">h1 {color: #fc0;}</style> </head> <body> <h1>Hello World!</h1> <p>:)</p> </body> </html>""" p.from_url(url) self.assertEqual(p.root_url, 'http://media.tannern.com') self.assertEqual(p.relative_url, 'http://media.tannern.com/pynliner/') p._get_soup() with mock.patch.object(Pynliner, '_get_url') as mocked: mocked.return_value = 'p {color: #999}' p._get_external_styles() self.assertEqual(p.style_string, "p {color: #999}") p._get_internal_styles() self.assertEqual(p.style_string, "p {color: #999}\nh1 {color: #fc0;}\n") p._get_styles() output = p.run() desired = u"""<?xml version='1.0' encoding='utf-8'?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test</title> </head> <body> <h1 style="color: #fc0">Hello World!</h1> <p style="color: #999">:)</p> </body> </html>""" self.assertEqual(output, desired) def test_overloaded_styles(self): html = '<style>h1 { color: red; } #test { color: blue; }</style>' \ '<h1 id="test">Hello world!</h1>' expected = '<h1 id="test" style="color: blue">Hello world!</h1>' output = Pynliner().from_string(html).run() self.assertEqual(expected, output) def test_unicode_content(self): html = u"""<h1>Hello World!</h1><p>\u2022 point</p>""" css = """h1 { color: red; }""" expected = u"""<h1 style="color: red">Hello World!</h1><p>\u2022 point</p>""" output = Pynliner().from_string(html).with_cssString(css).run() self.assertEqual(output, expected) def test_conditional_comments(self): html = "<!-- <normal> --><!--[if condition]><p>special</p><![endif]-->" expected = "<!-- <normal> --><!--[if condition]><p>special</p><![endif]-->" output = Pynliner(allow_conditional_comments=True).from_string(html).run() self.assertEqual(output, expected)
def setUp(self): self.html = """<style>.b1,.b2 { font-weight:bold; } .c {color: red}</style><span class="b1">Bold</span><span class="b2 c">Bold Red</span>""" self.p = Pynliner().from_string(self.html)
def test_08_fromURL(self): """Test 'fromURL' constructor""" url = 'http://media.tannern.com/pynliner/test.html' p = Pynliner() p.from_url(url) self.assertEqual(p.root_url, 'http://media.tannern.com') self.assertEqual(p.relative_url, 'http://media.tannern.com/pynliner/') p._get_soup() p._get_external_styles() self.assertEqual(p.style_string, "p {color: #999}") p._get_internal_styles() self.assertEqual(p.style_string, "p {color: #999}\nh1 {color: #ffcc00;}\n") p._get_styles() output = p.run() desired = u"""<?xml version='1.0' encoding='utf-8'?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test</title> </head> <body> <h1 style="color: #fc0">Hello World!</h1> <p style="color: #999">Possim tincidunt putamus iriure eu nulla. Facer qui volutpat ut aliquam sequitur. Mutationem legere feugiat autem clari notare. Nulla typi augue suscipit lectores in.</p> <p style="color: #999">Facilisis claritatem eum decima dignissim legentis. Nulla per legentis odio molestie quarta. Et velit typi claritas ipsum ullamcorper.</p> </body> </html>""" self.assertEqual(output, desired)
def test_overwrite_comma(self): """Test overwrite inline styles""" html = '<style>h1,h2,h3 {color: #000;}</style><h1 style="color: #fff">Foo</h1><h3 style="color: #fff">Foo</h3>' desired_output = '<h1 style="color: #000; color: #fff">Foo</h1><h3 style="color: #000; color: #fff">Foo</h3>' output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output)
def test_fromURL(self): """Test 'fromURL' constructor""" url = 'http://media.tannern.com/pynliner/test.html' p = Pynliner() with mock.patch.object(Pynliner, '_get_url') as mocked: mocked.return_value = u"""<?xml version='1.0' encoding='utf-8'?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test</title> <link rel="stylesheet" type="text/css" href="test.css"/> <style type="text/css">h1 {color: #fc0;}</style> </head> <body> <h1>Hello World!</h1> <p>:)</p> </body> </html>""" p.from_url(url) self.assertEqual(p.root_url, 'http://media.tannern.com') self.assertEqual(p.relative_url, 'http://media.tannern.com/pynliner/') p._get_soup() with mock.patch.object(Pynliner, '_get_url') as mocked: mocked.return_value = 'p {color: #999}' p._get_external_styles() self.assertEqual(p.style_string, "p {color: #999}") p._get_internal_styles() self.assertEqual(p.style_string, "p {color: #999}\nh1 {color: #fc0;}\n") p._get_styles() output = p.run() desired = u"""<?xml version='1.0' encoding='utf-8'?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test</title> </head> <body> <h1 style="color: #fc0">Hello World!</h1> <p style="color: #999">:)</p> </body> </html>""" self.assertEqual(output, desired)
def setUp(self): self.pyn = Pynliner(case_sensitive=False)
class Basic(unittest.TestCase): def setUp(self): self.html = "<html><head><style>h1 { color:#ffcc00; }</style></head><body><h1>Hello World!</h1></body></html>" self.p = Pynliner().from_string(self.html) def test_01_fromString(self): """Test 'fromString' constructor""" self.assertEqual(self.p.source_string, self.html) def test_02_get_soup(self): """Test '_get_soup' method""" self.p._get_soup() self.assertEqual(lxml.html.tostring(self.p.soup), self.html) def test_03_get_styles(self): """Test '_get_styles' method""" self.p._get_soup() self.p._get_styles() self.assertEqual(self.p.style_string, u'h1 { color:#ffcc00; }') self.assertEqual(lxml.html.tostring(self.p.soup), u'<html><head></head><body><h1>Hello World!</h1></body></html>') def test_04_apply_styles(self): """Test '_apply_styles' method""" self.p._get_soup() self.p._get_styles() self.p._apply_styles() self.assertEqual(lxml.html.tostring(self.p.soup), u'<html><head></head><body><h1 style="color: #fc0">Hello World!</h1></body></html>') def test_05_run(self): """Test 'run' method""" output = self.p.run() self.assertEqual(output, u'<html><head></head><body><h1 style="color: #fc0">Hello World!</h1></body></html>') def test_06_with_cssString(self): """Test 'with_cssString' method""" cssString = 'h1 {font-size: 2em;}' self.p = Pynliner().from_string(self.html).with_cssString(cssString) self.assertEqual(self.p.style_string, cssString + '\n') output = self.p.run() self.assertEqual(output, '<html><head></head><body><h1 style="font-size: 2em; color: #fc0">Hello World!</h1></body></html>') def test_07_fromString(self): """Test 'fromString' complete""" output = pynliner.fromString(self.html) desired = u'<html><head></head><body><h1 style="color: #fc0">Hello World!</h1></body></html>' self.assertEqual(output, desired) def test_08_fromURL(self): """Test 'fromURL' constructor""" url = 'https://raw.github.com/voidfiles/pynliner/master/test_data/test.html' p = Pynliner() p.from_url(url) self.assertEqual(p.root_url, 'https://raw.github.com') self.assertEqual(p.relative_url, 'https://raw.github.com/voidfiles/pynliner/master/test_data/') p._get_soup() p._get_external_styles() self.assertEqual(p.style_string, "p {color: #999}") p._get_internal_styles() self.assertEqual(p.style_string, "p {color: #999}\nh1 {color: #ffcc00;}") p._get_styles() output = p.run() desired = u"""<html><head></head><body>\n <h1 style="color: #fc0">Testing Title</h1>\n <p style="color: #999">Awesome</p>\n </body></html>""" self.assertEqual(output, desired) def test_09_overloadedStyles(self): html = '<style>h1 { color: red; } #test { color: blue; }</style><h1 id="test">Hello world!</h1>' expected = '<html><head></head><body><h1 id="test" style="color: blue">Hello world!</h1></body></html>' output = Pynliner().from_string(html).run() self.assertEqual(expected, output)
# choose a random problem max_set, max_prob = 427, 4 while True: try: prob_code = (randint(1, max_set), chr(randint(0, max_prob) + 65)) if prob_code in used_probs: raise Exception('This code is terrible.') if not get_problem_html(prob_code): raise Exception('This code is terrible.') ufile.write(str(prob_code) + '\n') break except: pass out.append('<hr>') out.append('</body>') out.append('</html>') preinline_html = '\n'.join(out) final_p = Pynliner().from_string(preinline_html).with_cssString(css_string) final_html = final_p.run() print final_html
class Basic(unittest.TestCase): def setUp(self): self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" self.p = Pynliner().from_string(self.html) def test_01_fromString(self): """Test 'fromString' constructor""" self.assertEqual(self.p.source_string, self.html) def test_02_get_soup(self): """Test '_get_soup' method""" self.p._get_soup() self.assertEqual(unicode(self.p.soup), self.html) def test_03_get_styles(self): """Test '_get_styles' method""" self.p._get_soup() self.p._get_styles() self.assertEqual(self.p.style_string, u'h1 { color:#ffcc00; }\n') self.assertEqual(unicode(self.p.soup), u'<h1>Hello World!</h1>') def test_04_apply_styles(self): """Test '_apply_styles' method""" self.p._get_soup() self.p._get_styles() self.p._apply_styles() self.assertEqual(unicode(self.p.soup), u'<h1 style="color: #fc0">Hello World!</h1>') def test_05_run(self): """Test 'run' method""" output = self.p.run() self.assertEqual(output, u'<h1 style="color: #fc0">Hello World!</h1>') def test_06_with_cssString(self): """Test 'with_cssString' method""" cssString = 'h1 {font-size: 2em;}' self.p = Pynliner().from_string(self.html).with_cssString(cssString) self.assertEqual(self.p.style_string, cssString + '\n') output = self.p.run() self.assertEqual(output, u'<h1 style="font-size: 2em; color: #fc0">Hello World!</h1>') def test_07_fromString(self): """Test 'fromString' complete""" output = pynliner.fromString(self.html) desired = u'<h1 style="color: #fc0">Hello World!</h1>' self.assertEqual(output, desired) def test_08_fromURL(self): """Test 'fromURL' constructor""" url = 'http://media.tannern.com/pynliner/test.html' p = Pynliner() p.from_url(url) self.assertEqual(p.root_url, 'http://media.tannern.com') self.assertEqual(p.relative_url, 'http://media.tannern.com/pynliner/') p._get_soup() p._get_external_styles() self.assertEqual(p.style_string, "p {color: #999}") p._get_internal_styles() self.assertEqual(p.style_string, "p {color: #999}\nh1 {color: #ffcc00;}\n") p._get_styles() output = p.run() desired = u"""<?xml version='1.0' encoding='utf-8'?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test</title> </head> <body> <h1 style="color: #fc0">Hello World!</h1> <p style="color: #999">Possim tincidunt putamus iriure eu nulla. Facer qui volutpat ut aliquam sequitur. Mutationem legere feugiat autem clari notare. Nulla typi augue suscipit lectores in.</p> <p style="color: #999">Facilisis claritatem eum decima dignissim legentis. Nulla per legentis odio molestie quarta. Et velit typi claritas ipsum ullamcorper.</p> </body> </html>""" self.assertEqual(output, desired)
# Getting email.css print "\nGetting CSS..." cssFile = open(os.path.join(templateDir, "css/email.css"), "r") css = cssFile.read(); cssFile.close() for name in files: print " Found: " + name output = name.replace(".template.html", ".html") if doInlining: inputFile = open(name, 'r') origEmail = inputFile.read() inputFile.close() inliner = Pynliner().from_string(origEmail).with_cssString(css) inlinedEmail = inliner.run() prettyEmail = BeautifulSoup(inlinedEmail).prettify() outputFile = open(output, "w") outputFile.write(prettyEmail) outputFile.close() print " Gen: " + output print "" return if __name__ == '__main__': sys.exit(main())
class CommaSelector(unittest.TestCase): def setUp(self): self.html = """<style>.b1,.b2 { font-weight:bold; } .c {color: red}</style><span class="b1">Bold</span><span class="b2 c">Bold Red</span>""" self.p = Pynliner().from_string(self.html) def test_01_fromString(self): """Test 'fromString' constructor""" self.assertEqual(self.p.source_string, self.html) def test_02_get_soup(self): """Test '_get_soup' method""" self.p._get_soup() self.assertEqual(unicode(self.p.soup), self.html) def test_03_get_styles(self): """Test '_get_styles' method""" self.p._get_soup() self.p._get_styles() self.assertEqual(self.p.style_string, u'.b1,.b2 { font-weight:bold; } .c {color: red}\n') self.assertEqual(unicode(self.p.soup), u'<span class="b1">Bold</span><span class="b2 c">Bold Red</span>') def test_04_apply_styles(self): """Test '_apply_styles' method""" self.p._get_soup() self.p._get_styles() self.p._apply_styles() self.assertEqual(unicode(self.p.soup), u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="font-weight: bold; color: red">Bold Red</span>') def test_05_run(self): """Test 'run' method""" output = self.p.run() self.assertEqual(output, u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="font-weight: bold; color: red">Bold Red</span>') def test_06_with_cssString(self): """Test 'with_cssString' method""" cssString = '.b1,.b2 {font-size: 2em;}' self.p = Pynliner().from_string(self.html).with_cssString(cssString) self.assertEqual(self.p.style_string, cssString + '\n') output = self.p.run() self.assertEqual(output, u'<span class="b1" style="font-size: 2em; font-weight: bold">Bold</span><span class="b2 c" style="font-size: 2em; font-weight: bold; color: red">Bold Red</span>') def test_07_fromString(self): """Test 'fromString' complete""" output = pynliner.fromString(self.html) desired = u'<span class="b1" style="font-weight: bold">Bold</span><span class="b2 c" style="font-weight: bold; color: red">Bold Red</span>' self.assertEqual(output, desired) def test_08_comma_whitespace(self): """Test excess whitespace in CSS""" html = '<style>h1, h2 ,h3,\nh4{ color: #000} </style><h1>1</h1><h2>2</h2><h3>3</h3><h4>4</h4>' desired_output = '<h1 style="color: #000">1</h1><h2 style="color: #000">2</h2><h3 style="color: #000">3</h3><h4 style="color: #000">4</h4>' output = Pynliner().from_string(html).run() self.assertEqual(output, desired_output)
class Basic(unittest.TestCase): def setUp(self): self.html = "<style>h1 { color:#ffcc00; }</style><h1>Hello World!</h1>" self.p = Pynliner().from_string(self.html) def test_01_fromString(self): """Test 'fromString' constructor""" self.assertEqual(self.p.source_string, self.html) def test_02_get_soup(self): """Test '_get_soup' method""" self.p._get_soup() self.assertEqual(unicode(self.p.soup), self.html) def test_03_get_styles(self): """Test '_get_styles' method""" self.p._get_soup() self.p._get_styles() self.assertEqual(self.p.style_string, u'h1 { color:#ffcc00; }\n') self.assertEqual(unicode(self.p.soup), u'<h1>Hello World!</h1>') def test_04_apply_styles(self): """Test '_apply_styles' method""" self.p._get_soup() self.p._get_styles() self.p._apply_styles() self.assertEqual(unicode(self.p.soup), u'<h1 style="color: #fc0">Hello World!</h1>') def test_05_run(self): """Test 'run' method""" output = self.p.run() self.assertEqual(output, u'<h1 style="color: #fc0">Hello World!</h1>') def test_06_with_cssString(self): """Test 'with_cssString' method""" cssString = 'h1 {font-size: 2em;}' self.p = Pynliner().from_string(self.html).with_cssString(cssString) self.assertEqual(self.p.style_string, cssString + '\n') output = self.p.run() self.assertEqual( output, u'<h1 style="font-size: 2em; color: #fc0">Hello World!</h1>') def test_07_fromString(self): """Test 'fromString' complete""" output = pynliner.fromString(self.html) desired = u'<h1 style="color: #fc0">Hello World!</h1>' self.assertEqual(output, desired) def test_08_fromURL(self): """Test 'fromURL' constructor""" url = 'http://media.tannern.com/pynliner/test.html' p = Pynliner() p.from_url(url) self.assertEqual(p.root_url, 'http://media.tannern.com') self.assertEqual(p.relative_url, 'http://media.tannern.com/pynliner/') p._get_soup() p._get_external_styles() self.assertEqual(p.style_string, "p {color: #999}") p._get_internal_styles() self.assertEqual(p.style_string, "p {color: #999}\nh1 {color: #ffcc00;}\n") p._get_styles() output = p.run() desired = u"""<?xml version='1.0' encoding='utf-8'?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>test</title> </head> <body> <h1 style="color: #fc0">Hello World!</h1> <p style="color: #999">Possim tincidunt putamus iriure eu nulla. Facer qui volutpat ut aliquam sequitur. Mutationem legere feugiat autem clari notare. Nulla typi augue suscipit lectores in.</p> <p style="color: #999">Facilisis claritatem eum decima dignissim legentis. Nulla per legentis odio molestie quarta. Et velit typi claritas ipsum ullamcorper.</p> </body> </html>""" self.assertEqual(output, desired)
from pynliner import Pynliner # from lxml.html.soupparser import fromstring from lxml.html import fromstring, tostring import sys from os import path, environ import re if len(sys.argv) == 1: target = sys.stdin else: target = open(sys.argv[1], 'r', encoding='utf-8') with target as f: #f_contents = f.read().replace('\r', '') f_contents = f.read() inliner = Pynliner() root = fromstring(f_contents) for element in root.iter('link'): if element.attrib['rel'] == 'stylesheet' and element.attrib['type'] == 'text/css': if target is sys.stdin: with open(path.join(environ['OTHER_SHEETS'], element.attrib['href'])) as cssf: cssf_contents = cssf.read() inliner.with_cssString(cssf_contents) else: with open(path.join(path.dirname(sys.argv[1]), element.attrib['href'])) as cssf: cssf_contents = cssf.read() inliner.with_cssString(cssf_contents) element.getparent().remove(element) for element in root.iter('div'):