Coverage for tests / integration / utils / run_api.py: 79%
33 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-03-20 10:09 -0400
« prev ^ index » next coverage.py v7.13.4, created at 2026-03-20 10:09 -0400
1import subprocess
2import os
3import requests
4import time
5import shutil
8def run_node_project(path: str, commands: list[str], port: str) -> subprocess.Popen:
9 """Runs a node project with the given commands and sets the PORT environment variable.
11 Args:
12 path (str): The path to the project
13 commands (list[str]): The list of commands
14 port (str): The port to set for the environment variable
16 Returns:
17 subprocess.Popen: The process object
18 """
19 # Set the environment variable
20 env = os.environ.copy()
21 env["PORT"] = port
22 shell_flag = os.name == "nt" # True no Windows, False no Linux/macOS
24 # Run npm install with proper handling
25 npm_cmd = shutil.which("npm")
26 node_cmd = shutil.which("node")
27 if npm_cmd is None:
28 raise RuntimeError("npm command not found. Please ensure Node.js is installed.")
30 try:
31 subprocess.run([npm_cmd, "install"], cwd=path, check=True, env=env, shell=shell_flag)
32 except subprocess.CalledProcessError as e:
33 print(f"npm install failed: {e}")
34 raise
36 # Run each command in the list
37 for command in commands:
38 subprocess.run(command.split(), cwd=path, check=True, env=env, shell=shell_flag)
40 # Run node server.js
41 process = subprocess.Popen([node_cmd, "server.js"], cwd=path, env=env, shell=shell_flag)
43 return process
46def wait_for_server(url, timeout=30):
47 """Wait for the server to start by continuously checking the given URL.
49 Args:
50 url (str): The URL to check.
51 timeout (int): Maximum time to wait for the server to start in seconds.
53 Returns:
54 bool: True if the server is ready, False if the timeout is reached.
55 """
56 start_time = time.time()
57 while time.time() - start_time < timeout:
58 try:
59 response = requests.get(url)
60 if response.status_code == 200:
61 return True
62 except requests.exceptions.ConnectionError:
63 pass
64 time.sleep(1)
65 return False