|
| 1 | +import bcrypt |
| 2 | +import os |
| 3 | +import subprocess |
| 4 | +import tempfile |
| 5 | +import threading |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | + |
| 9 | +class SelfossServerThread(threading.Thread): |
| 10 | + ''' |
| 11 | + A thread that starts and stops PHP’s built-in web server running selfoss. |
| 12 | + ''' |
| 13 | + def __init__(self, selfoss_root: Path, username: str, password: str, host_name: str, port: int): |
| 14 | + super().__init__() |
| 15 | + self.selfoss_root = selfoss_root |
| 16 | + self.username = username |
| 17 | + self.password = password |
| 18 | + self.host_name = host_name |
| 19 | + self.port = port |
| 20 | + |
| 21 | + def run(self): |
| 22 | + with tempfile.TemporaryDirectory() as temp_dir: |
| 23 | + # Set up data directories. |
| 24 | + temp_dir = Path(temp_dir) |
| 25 | + data_dir = temp_dir / 'data' |
| 26 | + (data_dir / 'sqlite').mkdir(parents=True) |
| 27 | + (data_dir / 'thumbnails').mkdir(parents=True) |
| 28 | + (data_dir / 'favicons').mkdir(parents=True) |
| 29 | + |
| 30 | + # Configure selfoss using environment variables for convenience. |
| 31 | + test_env = { |
| 32 | + **os.environ, |
| 33 | + 'SELFOSS_DATADIR': data_dir, |
| 34 | + 'SELFOSS_LOGGER_DESTINATION': 'error_log', |
| 35 | + 'SELFOSS_USERNAME': self.username, |
| 36 | + 'SELFOSS_PASSWORD': bcrypt.hashpw(self.password.encode('utf-8'), bcrypt.gensalt()), |
| 37 | + 'SELFOSS_DB_TYPE': 'sqlite', |
| 38 | + 'SELFOSS_PUBLIC': '1', |
| 39 | + 'SELFOSS_LOGGER_LEVEL': 'DEBUG', |
| 40 | + } |
| 41 | + |
| 42 | + current_dir = Path(__file__).parent.absolute() |
| 43 | + |
| 44 | + php_command = [ |
| 45 | + 'php', |
| 46 | + # We need to enable reading environment variables. |
| 47 | + '-d', 'variables_order=EGPCS', |
| 48 | + '-S', f'{self.host_name}:{self.port}', |
| 49 | + '-c', current_dir / 'php.ini', |
| 50 | + self.selfoss_root / 'run.php', |
| 51 | + ] |
| 52 | + |
| 53 | + # Create the subprocess. |
| 54 | + self.proc = subprocess.Popen( |
| 55 | + php_command, |
| 56 | + env=test_env, |
| 57 | + cwd=self.selfoss_root, |
| 58 | + ) |
| 59 | + |
| 60 | + # Wait for it to finish. |
| 61 | + self.proc.communicate() |
| 62 | + |
| 63 | + def stop(self): |
| 64 | + self.proc.kill() |
0 commit comments