Debian Codegraph @

tests/test_coverup_109.py

raw symbols SCIP
1 # file scalene/scalene_utility.py:186-211
2 # lines [186, 187, 190, 193, 194, 195, 196, 198, 207, 208, 209, 211]
3 # branches []
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 # Define a simple HTTP server for testing purposes
16 class TestHTTPServer(threading.Thread):
17 # Prevent pytest from considering this class as a test
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 # Use a common port for testing
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 # Create a temporary HTML file
45 temp_dir = tempfile.mkdtemp() # Create a new temporary directory
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) # Remove the temporary directory
51
52
53 def test_show_browser(temp_html_file, server, monkeypatch):
54 # Mock webbrowser.open to prevent actually opening the browser
55 def mock_open(url):
56 assert url == f"http://localhost:{server.port}/"
57
58 monkeypatch.setattr(webbrowser, "open", mock_open)
59
60 # Mock subprocess.Popen to prevent actually launching a server
61 class MockPopen:
62 def __init__(self, *args, **kwargs):
63 pass
64
65 monkeypatch.setattr("subprocess.Popen", MockPopen)
66
67 # Save the current working directory to restore later
68 curr_dir = os.getcwd()
69
70 # Run the function to test
71 show_browser(temp_html_file, server.port)
72
73 # Check if the current directory was restored
74 assert os.getcwd() == curr_dir