| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
import os |
| 6 |
import pytest |
| 7 |
import shutil |
| 8 |
import tempfile |
| 9 |
import threading |
| 10 |
import webbrowser |
| 11 |
from http.server import HTTPServer, SimpleHTTPRequestHandler |
| 12 |
from scalene.scalene_utility import show_browser |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
class TestHTTPServer(threading.Thread): |
| 17 |
|
| 18 |
__test__ = False |
| 19 |
|
| 20 |
def __init__(self, port): |
| 21 |
super().__init__() |
| 22 |
self.port = port |
| 23 |
self.httpd = HTTPServer(("localhost", self.port), SimpleHTTPRequestHandler) |
| 24 |
self.daemon = True |
| 25 |
|
| 26 |
def run(self): |
| 27 |
self.httpd.serve_forever() |
| 28 |
|
| 29 |
def stop(self): |
| 30 |
self.httpd.shutdown() |
| 31 |
|
| 32 |
|
| 33 |
@pytest.fixture(scope="module") |
| 34 |
def server(): |
| 35 |
port = 8000 |
| 36 |
server = TestHTTPServer(port) |
| 37 |
server.start() |
| 38 |
yield server |
| 39 |
server.stop() |
| 40 |
|
| 41 |
|
| 42 |
@pytest.fixture(scope="module") |
| 43 |
def temp_html_file(): |
| 44 |
|
| 45 |
temp_dir = tempfile.mkdtemp() |
| 46 |
file_path = os.path.join(temp_dir, "index.html") |
| 47 |
with open(file_path, "w") as f: |
| 48 |
f.write("<html><body><h1>Test Page</h1></body></html>") |
| 49 |
yield file_path |
| 50 |
shutil.rmtree(temp_dir) |
| 51 |
|
| 52 |
|
| 53 |
def test_show_browser(temp_html_file, server, monkeypatch): |
| 54 |
|
| 55 |
def mock_open(url): |
| 56 |
assert url == f"http://localhost:{server.port}/" |
| 57 |
|
| 58 |
monkeypatch.setattr(webbrowser, "open", mock_open) |
| 59 |
|
| 60 |
|
| 61 |
class MockPopen: |
| 62 |
def __init__(self, *args, **kwargs): |
| 63 |
pass |
| 64 |
|
| 65 |
monkeypatch.setattr("subprocess.Popen", MockPopen) |
| 66 |
|
| 67 |
|
| 68 |
curr_dir = os.getcwd() |
| 69 |
|
| 70 |
|
| 71 |
show_browser(temp_html_file, server.port) |
| 72 |
|
| 73 |
|
| 74 |
assert os.getcwd() == curr_dir |