diff --git a/libzim/wrapper.pyx b/libzim/wrapper.pyx index 3b0627e6..ab8e5e0e 100644 --- a/libzim/wrapper.pyx +++ b/libzim/wrapper.pyx @@ -322,6 +322,18 @@ cdef class ReadArticle: """Get if the article is a redirect""" return self.c_article.isRedirect() + def get_redirect_article(self) -> ReadArticle: + """ Target ReadArticle of this one """ + if not self.is_redirect: + raise RuntimeError("Article is not a redirect") + + cdef wrapper.Article art = self.c_article.getRedirectArticle() + if not art.good(): + raise RuntimeError("Redirect article not found") + + article = ReadArticle.from_read_article(art) + return article + def __repr__(self): return f"{self.__class__.__name__}(url={self.longurl}, title=)" diff --git a/tests/test_libzim_file_reader.py b/tests/test_libzim_file_reader.py index eb376e89..53cf6940 100644 --- a/tests/test_libzim_file_reader.py +++ b/tests/test_libzim_file_reader.py @@ -114,3 +114,16 @@ def test_get_wrong_article(reader): reader.get_article_by_id(reader.article_count + 100) with pytest.raises(RuntimeError): reader.get_article("A/I_do_not_exists") + + +def test_redirects(reader): + # we can access target article from a redirect one + abundante = reader.get_article("A/Abundante") + assert abundante.is_redirect + target = abundante.get_redirect_article() + assert target.longurl != abundante.longurl + + # we can't access a target on non-redirect articles + assert target.is_redirect is False + with pytest.raises(RuntimeError): + target.get_redirect_article()