forked from csernazs/pytest-httpserver
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpytest_plugin.py
More file actions
102 lines (72 loc) · 2.3 KB
/
pytest_plugin.py
File metadata and controls
102 lines (72 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
import os
import pytest
from .httpserver import HTTPServer, HTTPProxy
class Plugin:
SERVER = None
PROXY = None
class PluginHTTPServer(HTTPServer):
def start(self):
super().start()
Plugin.SERVER = self
def stop(self):
super().stop()
Plugin.SERVER = None
class PluginHTTPProxy(HTTPProxy):
def start(self):
super().start()
Plugin.PROXY = self
def stop(self):
super().stop()
Plugin.PROXY = None
@pytest.fixture(scope="session")
def plugin_httpserver_class():
yield PluginHTTPServer
@pytest.fixture(scope="session")
def plugin_proxy_class():
print("plugin_proxy_class")
yield PluginHTTPProxy
def get_httpserver_listen_address():
listen_host = os.environ.get("PYTEST_HTTPSERVER_HOST")
listen_port = os.environ.get("PYTEST_HTTPSERVER_PORT")
if listen_port:
listen_port = int(listen_port)
return (listen_host, listen_port)
@pytest.fixture
def httpserver_listen_address():
return get_httpserver_listen_address()
@pytest.fixture
def httpserver(httpserver_listen_address, plugin_httpserver_class):
if Plugin.SERVER:
Plugin.SERVER.clear()
yield Plugin.SERVER
return
host, port = httpserver_listen_address
if not host:
host = HTTPServer.DEFAULT_LISTEN_HOST
if not port:
port = HTTPServer.DEFAULT_LISTEN_PORT
server = plugin_httpserver_class(host=host, port=port)
server.start()
yield server
@pytest.fixture
def httpproxy(httpserver_listen_address, tmp_path, plugin_proxy_class):
if Plugin.PROXY:
Plugin.PROXY.clear()
yield Plugin.PROXY
return
host, port = httpserver_listen_address
if not host:
host = HTTPProxy.DEFAULT_LISTEN_HOST
if not port:
port = HTTPProxy.DEFAULT_LISTEN_PORT
ca_dir = tmp_path.joinpath("httpproxy_ca")
ca_dir.mkdir(exist_ok=True)
server = plugin_proxy_class(host=host, port=port, proxy_options={"ca_file_cache": str(ca_dir.joinpath("wsgiprox-ca.pem"))})
server.start()
yield server
def pytest_sessionfinish(session, exitstatus): # pylint: disable=unused-argument
for instance in (Plugin.SERVER, Plugin.PROXY):
if instance is not None:
instance.clear()
if instance.is_running():
instance.stop()