Fichiers
meteo-vercors/forum/tests/test_publier.py
T

203 lignes
13 KiB
Python

"""Page « Publier » : Markdown sûr, tableaux, brouillons privés, publication (vrai HTTP local, SQLite jetable)."""
import json
import re
import unittest
from urllib.parse import urlencode
import test_forum as base
import markdown_sur
from forum import Invalide
class TestMarkdown(unittest.TestCase):
def test_html_echappe_et_liens_surs(self):
h = markdown_sur.rendu("<script>alert(1)</script>\n<img src=x onerror=alert(1)>")
self.assertNotIn("<script", h)
self.assertNotIn("<img", h)
self.assertIn("&lt;script&gt;", h)
for piege in ("[clic](javascript:alert(1))", "[clic](JaVaScRiPt:alert(1))", "[x](data:text/html,a)",
"[x](/relatif)", "[x](https://a.fr\"onclick=alert(1))", "[x](https://a.fr'onmouseover='alert(1))"):
h = markdown_sur.rendu(piege)
self.assertNotIn("href='javascript", h.lower())
self.assertNotRegex(h, r"<a [^>]*\s(onclick|onmouseover)=")
self.assertNotIn("href='data", h)
self.assertNotIn("href='/", h)
h = markdown_sur.rendu("[Météo](https://vercors.me/?a=1&b=2)")
self.assertIn("<a href='https://vercors.me/?a=1&amp;b=2' rel='nofollow noopener noreferrer'>Météo</a>", h)
def test_mise_en_forme(self):
h = markdown_sur.rendu("# Titre\n\n**gras** et *ita* et _ita2_ et `<b>code</b>`\nligne 2\n\n- un\n- deux\n\n1. a\n2. b")
self.assertIn("<h2>Titre</h2>", h)
self.assertIn("<strong>gras</strong>", h)
self.assertIn("<em>ita</em>", h)
self.assertIn("<em>ita2</em>", h)
self.assertIn("<code>&lt;b&gt;code&lt;/b&gt;</code>", h)
self.assertIn("<br>ligne 2</p>", h)
self.assertIn("<ul><li>un</li><li>deux</li></ul>", h)
self.assertIn("<ol><li>a</li><li>b</li></ol>", h)
self.assertIn("<code>**pas gras**</code>", markdown_sur.rendu("`**pas gras**`"))
def test_caracteres_de_controle(self):
h = markdown_sur.rendu("a \x005\x00 `c` \x000\x00 b\x07")
self.assertNotIn("\x00", h)
self.assertIn("<code>c</code>", h)
self.assertEqual(markdown_sur._en_ligne("\x009\x00"), "\x009\x00") # marqueur inconnu : pas d'IndexError
f = base.Forum()
u = f.fixer_proprietaire("theo", "Théo")
for titre, corps in (("t\x00", "c"), ("t", "a\x005\x00")):
with self.assertRaises(Invalide):
f.creer_sujet(u, titre, corps)
f.creer_sujet(u, "t", "ligne\r\nsuite\ttab") # retours à la ligne et tabulations restent permis
def test_entrees_pieges_rapides(self):
import time
for piege in ("# " + " " * 20000 + "x", "#" * 3 + " " + "#" * 20000 + " x", "**" + "a " * 20000,
"*a" * 20000, "_a " * 20000, "| " * 20000 + "\n|" + "-|" * 20000, "[" * 20000 + "](" * 20000):
debut = time.perf_counter()
markdown_sur.rendu(piege)
self.assertLess(time.perf_counter() - debut, 1.0, piege[:20])
self.assertIn("<h2>Titre</h2>", markdown_sur.rendu("# Titre ## "))
self.assertNotIn("<h2>", markdown_sur.rendu("# ###"))
def test_tableaux(self):
h = markdown_sur.rendu("| Station | Tmin | Note |\n| --- | ---: | :-: |\n| Gêve | -4,2 | **gel** |\n| <i>x</i> | 1 |")
self.assertIn("<table>", h)
self.assertIn("<th>Station</th><th class='droite'>Tmin</th><th class='centre'>Note</th>", h)
self.assertIn("<td>Gêve</td><td class='droite'>-4,2</td><td class='centre'><strong>gel</strong></td>", h)
self.assertIn("<td>&lt;i&gt;x&lt;/i&gt;</td><td class='droite'>1</td><td class='centre'></td>", h) # cellule manquante complétée
self.assertNotIn("<table>", markdown_sur.rendu("a | b\nc | d")) # sans ligne de séparation : texte
class TestPublier(base.BaseHTTP):
def post(self, chemin, qui, champs, **kw):
return self.req(chemin, qui, urlencode(champs).encode(), **kw)
def test_page_et_bouton_entete(self):
page = self.req("/publier", "a1")[2].decode()
self.assertNotIn("class='bouton principal publier'", page) # plus de bouton Publier dans l'en-tête (Théo, 06/11)
self.assertIn("href='/brouillons'>Mes brouillons</a>", page)
for libelle in ("for='titre'", "for='station'", "for='corps'", "for='photos'", "Me prévenir des réponses",
"Catégorie <span class='etat'>bientôt</span>", "Enregistrer le brouillon", "formnovalidate"):
self.assertIn(libelle, page)
self.assertNotRegex(page, r"name='prevenir' value='1' checked") # décochée par défaut
self.assertIn("Gêve", page) # liste des stations
self.assertEqual(self.req("/publier", "m1")[0], 403)
self.assertNotIn("href='/publier'", self.req("/", "m1")[2].decode())
self.assertNotIn("Mes brouillons", self.req("/", "m1")[2].decode())
def test_publication_markdown_et_brouillon_supprime(self):
st, _, b = self.post("/brouillon", "a1", {"titre": "Gel", "corps": "brouillon", "station": "geve"})
bid = json.loads(b)["id"]
self.assertRegex(json.loads(b)["heure"], r"^\d{1,2} h \d{2}$")
corps = "## Relevés\n\n| Station | Tmin |\n| --- | --- |\n| Gêve | -4 |\n\n<script>alert(1)</script> [x](javascript:alert(1))"
st, h, _ = self.post("/publier", "a1", {"brouillon": bid, "titre": "Gel <b>matinal</b>", "corps": corps,
"station": "geve", "prevenir": "1", "action": "publier"})
self.assertEqual(st, 303)
tid = int(re.search(r"/t/(\d+)", h["Location"]).group(1))
page = self.req(h["Location"])[2].decode()
self.assertIn("<div class='message md'><h3>Relevés</h3>", page)
self.assertIn("<td>Gêve</td><td>-4</td>", page)
self.assertNotIn("<script>alert", page)
self.assertNotIn("href='javascript", page)
self.assertIn("Gel &lt;b&gt;matinal&lt;/b&gt;", page)
self.assertIn("Station liée : <b>", page)
t = self.f.con.execute("SELECT prevenir, station_liee FROM topics WHERE id=?", (tid,)).fetchone()
self.assertEqual((t[0], t[1]), (1, "geve"))
self.assertEqual(self.f.con.execute("SELECT format FROM posts WHERE topic_id=?", (tid,)).fetchone()[0], "md")
self.assertEqual(self.f.brouillons(self.adh), [])
# Les anciens messages (format texte) restent affichés tels quels
ancien = self.f.creer_sujet(self.adh, "Ancien", "**pas gras**\n<i>x</i>")
page = self.req("/t/%d" % ancien)[2].decode()
self.assertIn("<p class='message'>**pas gras**\n&lt;i&gt;x&lt;/i&gt;</p>", page)
def test_brouillons_prives(self):
bid, _ = self.f.enregistrer_brouillon(self.adh, 0, "SECRET_TITRE", "SECRET_CORPS")
self.assertIn("SECRET_TITRE", self.req("/brouillons", "a1")[2].decode())
self.assertIn("SECRET_CORPS", self.req("/publier?brouillon=%d" % bid, "a1")[2].decode())
for qui in ("theo", "pere"): # même le propriétaire ne voit pas le brouillon d'un autre
self.assertNotIn("SECRET_TITRE", self.req("/brouillons", qui)[2].decode())
st, _, b = self.req("/publier?brouillon=%d" % bid, qui)
self.assertEqual(st, 404)
self.assertNotIn("SECRET", b.decode())
self.assertEqual(self.post("/brouillon", qui, {"brouillon": bid, "titre": "pirate", "corps": "x"})[0], 400)
self.assertEqual(self.post("/brouillon/supprimer", qui, {"brouillon": bid})[0], 400)
self.assertEqual(self.post("/publier", qui, {"brouillon": bid, "titre": "t", "corps": "c", "action": "publier"})[0], 400)
self.assertEqual(self.req("/brouillons")[0], 403)
self.assertEqual(self.post("/brouillon", None, {"titre": "x"})[0], 403)
self.assertEqual(self.post("/brouillon", "m1", {"titre": "x"})[0], 403) # membre sans droit creer_sujet
self.assertEqual(self.f.brouillon(self.adh, bid)["titre"], "SECRET_TITRE")
with self.assertRaises(Invalide):
self.f.brouillon(self.theo, bid)
# contrôle d'origine, comme les autres POST
self.assertEqual(self.post("/brouillon", "a1", {"brouillon": bid, "titre": "x"}, origine=False)[0], 403)
self.assertEqual(self.f.brouillon(self.adh, bid)["titre"], "SECRET_TITRE")
def test_brouillon_sans_js_reprise_et_suppression(self):
st, h, _ = self.post("/publier", "a1", {"titre": "Neige", "corps": "début", "station": "geve", "action": "brouillon"})
self.assertEqual(st, 303)
self.assertRegex(h["Location"], r"^/publier\?brouillon=\d+&suite=enregistre$")
page = self.req(h["Location"], "a1")[2].decode()
self.assertRegex(page, r"Enregistré à \d{1,2} h \d{2}\.")
self.assertIn("value='Neige'", page)
self.assertIn("<option value='geve' selected>", page)
bid = int(h["Location"].split("=")[1].split("&")[0])
# mise à jour du même brouillon, puis aperçu sans JS
self.post("/publier", "a1", {"brouillon": bid, "titre": "Neige fraîche", "corps": "**10 cm**", "action": "brouillon"})
self.assertEqual(len(self.f.brouillons(self.adh)), 1)
st, _, b = self.post("/publier", "a1", {"brouillon": bid, "titre": "Neige fraîche", "corps": "**10 cm**", "action": "apercu"})
self.assertEqual(st, 200)
self.assertIn("<strong>10 cm</strong>", b.decode())
page = self.req("/brouillons", "a1")[2].decode()
self.assertIn("href='/publier?brouillon=%d'>Reprendre</a>" % bid, page)
self.assertEqual(self.post("/brouillon/supprimer", "a1", {"brouillon": bid})[0], 303)
self.assertIn("Aucun brouillon", self.req("/brouillons", "a1")[2].decode())
def test_apercu_instantane_et_validation(self):
st, _, b = self.post("/apercu-md", "a1", {"corps": "<script>x</script>| a | b |\n|---|---|\n| 1 | 2 |"})
self.assertEqual(st, 200)
self.assertNotIn("<script>", b.decode())
self.assertIn("<td>1</td><td>2</td>", b.decode())
self.assertEqual(self.post("/apercu-md", "a1", {"corps": "x"}, origine=False)[0], 403)
self.assertEqual(self.post("/apercu-md", "m1", {"corps": "x"})[0], 200) # un membre peut répondre, donc prévisualiser
self.assertEqual(self.post("/apercu-md", None, {"corps": "x"})[0], 403)
st, _, b = self.post("/publier", "a1", {"titre": "Sans corps", "corps": " ", "action": "publier"})
self.assertEqual(st, 400)
self.assertIn("value='Sans corps'", b.decode()) # rien n'est perdu
self.assertEqual(self.post("/publier", "a1", {"titre": "t", "corps": "c", "station": "inconnue", "action": "publier"})[0], 400)
# photos : même validation que creer_sujet
corps = (b'--P\r\nContent-Disposition: form-data; name="titre"\r\n\r\nPhoto\r\n'
b'--P\r\nContent-Disposition: form-data; name="corps"\r\n\r\nTexte\r\n'
b'--P\r\nContent-Disposition: form-data; name="photos"; filename="x.png"\r\nContent-Type: image/png\r\n\r\ninvalide\r\n--P--\r\n')
self.assertEqual(self.req("/publier", "a1", corps, "multipart/form-data; boundary=P")[0], 400)
corps = corps.replace(b"invalide", base.png())
st, h, _ = self.req("/publier", "a1", corps, "multipart/form-data; boundary=P")
self.assertEqual(st, 303)
self.assertIn("/photo/", self.req(h["Location"])[2].decode())
if __name__ == "__main__":
unittest.main()
class TestRepondrePleinePage(base.BaseHTTP):
def post(self, chemin, qui, champs, **kw):
return self.req(chemin, qui, urlencode(champs).encode(), **kw)
def test_barre_puis_page_de_reponse_en_markdown(self):
st, h, _ = self.post("/publier", "a1", {"titre": "Sujet ouvert", "corps": "Premier", "action": "publier"})
self.assertEqual(st, 303)
tid = int(re.search(r"/t/(\d+)", h["Location"]).group(1))
page = self.req("/t/%d" % tid, "m1")[2].decode()
self.assertIn("class='barre-repondre' href='/publier?sujet=%d'" % tid, page)
self.assertNotIn("id='reponse'", page) # plus de grand champ dans le sujet
st, _, b = self.req("/publier?sujet=%d" % tid, "m1")
self.assertEqual(st, 200)
self.assertIn("name='sujet' value='%d'" % tid, b.decode())
st, _, _ = self.post("/publier", "m1", {"sujet": str(tid), "corps": "| a | b |\n|---|---|\n| 1 | 2 |", "action": "publier"})
self.assertEqual(st, 303)
self.assertIn("<td>1</td><td>2</td>", self.req("/t/%d" % tid, "m1")[2].decode())
# Bulletin (sujet 1) : un membre n'a pas la barre ni le droit d'y publier
self.assertNotIn("class='barre-repondre'", self.req("/t/1", "m1")[2].decode())
self.assertEqual(self.post("/publier", "m1", {"sujet": "1", "corps": "x", "action": "publier"})[0], 403)