|
| 1 | +"""test view handler""" |
| 2 | +from html.parser import HTMLParser |
| 3 | + |
| 4 | +import pytest |
| 5 | +import tornado |
| 6 | + |
| 7 | +from jupyter_server.utils import url_path_join |
| 8 | +from .utils import expected_http_error |
| 9 | + |
| 10 | + |
| 11 | +class IFrameSrcFinder(HTMLParser): |
| 12 | + """Minimal HTML parser to find iframe.src attr""" |
| 13 | + |
| 14 | + def __init__(self): |
| 15 | + super().__init__() |
| 16 | + self.iframe_src = None |
| 17 | + |
| 18 | + def handle_starttag(self, tag, attrs): |
| 19 | + if tag.lower() == "iframe": |
| 20 | + for attr, value in attrs: |
| 21 | + if attr.lower() == "src": |
| 22 | + self.iframe_src = value |
| 23 | + return |
| 24 | + |
| 25 | + |
| 26 | +def find_iframe_src(html): |
| 27 | + """Find the src= attr of an iframe on the page |
| 28 | +
|
| 29 | + Assumes only one iframe |
| 30 | + """ |
| 31 | + finder = IFrameSrcFinder() |
| 32 | + finder.feed(html) |
| 33 | + return finder.iframe_src |
| 34 | + |
| 35 | + |
| 36 | +@pytest.mark.parametrize( |
| 37 | + "exists, name", |
| 38 | + [ |
| 39 | + (False, "nosuchfile.html"), |
| 40 | + (False, "nosuchfile.bin"), |
| 41 | + (True, "exists.html"), |
| 42 | + (True, "exists.bin"), |
| 43 | + ], |
| 44 | +) |
| 45 | +async def test_view(jp_fetch, jp_serverapp, jp_root_dir, exists, name): |
| 46 | + """Test /view/$path for a few cases""" |
| 47 | + if exists: |
| 48 | + jp_root_dir.joinpath(name).write_text(name) |
| 49 | + |
| 50 | + if not exists: |
| 51 | + with pytest.raises(tornado.httpclient.HTTPClientError) as e: |
| 52 | + await jp_fetch("view", name, method="GET") |
| 53 | + assert expected_http_error(e, 404), [name, e] |
| 54 | + else: |
| 55 | + r = await jp_fetch("view", name, method="GET") |
| 56 | + assert r.code == 200 |
| 57 | + assert r.headers["content-type"] == "text/html; charset=UTF-8" |
| 58 | + html = r.body.decode() |
| 59 | + src = find_iframe_src(html) |
| 60 | + assert src == url_path_join(jp_serverapp.base_url, f"/files/{name}") |
0 commit comments