Debian Codegraph @

tests/test_coverup_87.py

raw symbols SCIP
1 # file scalene/launchbrowser.py:148-169
2 # lines [148, 149, 150, 152, 153, 154, 155, 156, 157, 158, 159, 160, 162, 163, 165, 168, 169]
3 # branches ['149->150', '149->152', '153->154', '153->156']
4
5 import os
6 import pytest
7 import shutil
8 import tempfile
9 import threading
10 import time
11 import webbrowser
12 from unittest.mock import patch
13
14 # Mocks for the functions and variables not provided in the snippet
15 HOST = "localhost"
16
17
18 def run_server(host, port):
19 pass
20
21
22 def monitor_heartbeat():
23 pass
24
25
26 def generate_html(input_file, output_file):
27 with open(output_file, "w") as f:
28 f.write("<html><body>Demo</body></html>")
29
30
31 class Filename(str):
32 pass
33
34
35 def is_port_available(port):
36 return True
37
38
39 def start(filename: str, port: int) -> None:
40 while not is_port_available(port):
41 port += 1
42
43 cwd = os.getcwd()
44 if filename == "demo":
45 generate_html(Filename("demo"), Filename("demo.html"))
46 filename = "demo.html"
47 shutil.copy(filename, os.path.join(tempfile.gettempdir(), "index.html"))
48 os.chdir(tempfile.gettempdir())
49 server_thread = threading.Thread(target=run_server, args=[HOST, port])
50 server_thread.start()
51 threading.Thread(target=monitor_heartbeat).start()
52
53 webbrowser.open_new(f"http://{HOST}:{port}/")
54 server_thread.join()
55
56 os.chdir(cwd)
57
58 # Optional: a delay to ensure all resources are released
59 time.sleep(1)
60 os._exit(0) # Forcefully stops the program
61
62
63 @pytest.fixture
64 def setup_and_teardown():
65 # Setup
66 original_cwd = os.getcwd()
67 temp_dir = tempfile.gettempdir()
68 temp_index_html = os.path.join(temp_dir, "index.html")
69 # Store the original file if it exists
70 original_index_html = temp_index_html + ".bak"
71 if os.path.exists(temp_index_html):
72 shutil.move(temp_index_html, original_index_html)
73 yield temp_dir, original_cwd
74 # Teardown
75 os.chdir(original_cwd)
76 if os.path.exists(original_index_html):
77 shutil.move(original_index_html, temp_index_html)
78
79
80 def test_start(setup_and_teardown):
81 temp_dir, original_cwd = setup_and_teardown
82 test_port = 8000
83 test_filename = "test.html"
84 with open(test_filename, "w") as f:
85 f.write("<html><body>Test</body></html>")
86 with patch("webbrowser.open_new") as mock_open_new:
87 with patch("os._exit") as mock_exit:
88 with patch("scalene.launchbrowser.is_port_available", return_value=True):
89 start(test_filename, test_port)
90 mock_open_new.assert_called_with(f"http://{HOST}:{test_port}/")
91 mock_exit.assert_called_with(0)
92 assert os.path.exists(os.path.join(temp_dir, "index.html"))
93 with open(os.path.join(temp_dir, "index.html"), "r") as f:
94 content = f.read()
95 assert content == "<html><body>Test</body></html>"
96 os.remove(test_filename)