import sys
import unittest
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

from crawl import detecta_erro_yii, filtrar, normalizar_link


class CrawlTest(unittest.TestCase):
    def test_exclui_destrutivas(self):
        self.assertEqual(
            filtrar(["/x/delete?id=1", "/site/logout", "/x/view?id=1", "/site/inventario-resposta-exclui"]),
            ["/x/view?id=1"])

    def test_link_mesmo_host(self):
        self.assertEqual(normalizar_link("http://localhost:8074/a/b?c=1#x", "http://localhost:8074"), "/a/b?c=1")
        self.assertEqual(normalizar_link("/a/b", "http://localhost:8074"), "/a/b")

    def test_link_externo_ou_vazio(self):
        self.assertIsNone(normalizar_link("https://www.google.com/x", "http://localhost:8074"))
        self.assertIsNone(normalizar_link("#", "http://localhost:8074"))
        self.assertIsNone(normalizar_link("javascript:void(0)", "http://localhost:8074"))
        self.assertIsNone(normalizar_link("mailto:a@b.c", "http://localhost:8074"))

    def test_link_de_arquivo_estatico_ignorado(self):
        self.assertIsNone(normalizar_link("/uploads/a.pdf", "http://localhost:8074"))
        self.assertIsNone(normalizar_link("/assets/abc/x.js", "http://localhost:8074"))

    def test_detecta_erro_yii(self):
        self.assertTrue(detecta_erro_yii('<div class="site-error"><h1>Internal Server Error</h1></div>'))
        self.assertFalse(detecta_erro_yii("<div class='conteudo'>ok</div>"))


if __name__ == "__main__":
    unittest.main()
