xvfbwrapper 0.2.10__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2012-2025 Corey Goldberg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,273 @@
1
+ Metadata-Version: 2.2
2
+ Name: xvfbwrapper
3
+ Version: 0.2.10
4
+ Summary: Manage headless displays with Xvfb (X virtual framebuffer)
5
+ Home-page: https://github.com/cgoldberg/xvfbwrapper
6
+ Download-URL: https://pypi.org/project/xvfbwrapper
7
+ Author: Corey Goldberg
8
+ License: MIT
9
+ Keywords: xvfb,headless,virtual,display,x11,testing
10
+ Classifier: Environment :: X11 Applications
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: POSIX
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: Unix
18
+ Classifier: Programming Language :: Python
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.8
21
+ Classifier: Programming Language :: Python :: 3.9
22
+ Classifier: Programming Language :: Python :: 3.10
23
+ Classifier: Programming Language :: Python :: 3.11
24
+ Classifier: Programming Language :: Python :: 3.12
25
+ Classifier: Programming Language :: Python :: 3.13
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Description-Content-Type: text/x-rst
28
+ License-File: LICENSE
29
+ Dynamic: author
30
+ Dynamic: classifier
31
+ Dynamic: description
32
+ Dynamic: description-content-type
33
+ Dynamic: download-url
34
+ Dynamic: home-page
35
+ Dynamic: keywords
36
+ Dynamic: license
37
+ Dynamic: summary
38
+
39
+
40
+ ===============
41
+ xvfbwrapper
42
+ ===============
43
+
44
+
45
+ **Manage headless displays with Xvfb (X virtual framebuffer)**
46
+
47
+ ----
48
+
49
+ ---------
50
+ Info:
51
+ ---------
52
+
53
+ - Development: https://github.com/cgoldberg/xvfbwrapper
54
+ - Releases: https://pypi.org/project/xvfbwrapper
55
+ - Author: `Corey Goldberg <https://github.com/cgoldberg>`_ - 2012-2025
56
+ - License: MIT
57
+
58
+ ----
59
+
60
+ ----------------------
61
+ About xvfbwrapper:
62
+ ----------------------
63
+
64
+ `xvfbwrapper` is a python module for controlling virtual displays with Xvfb.
65
+
66
+ ----
67
+
68
+ ------------------
69
+ What is Xvfb?:
70
+ ------------------
71
+
72
+ `Xvfb` (X virtual framebuffer) is a display server implementing the X11 display server protocol.
73
+ It runs in memory and does not require a physical display or input devices. Only a network layer is necessary.
74
+
75
+ `Xvfb` is useful for running acceptance tests on headless servers.
76
+
77
+ ----
78
+
79
+ ----------------------------------
80
+ Install xvfbwrapper from PyPI:
81
+ ----------------------------------
82
+
83
+ .. code:: bash
84
+
85
+ pip install xvfbwrapper
86
+
87
+ ----
88
+
89
+ ------------------------
90
+ System Requirements:
91
+ ------------------------
92
+
93
+ * Python 3.8+
94
+ * X Window System
95
+ * Xvfb (`sudo apt-get install xvfb`, `yum install xorg-x11-server-Xvfb`, etc)
96
+ * File locking with `fcntl`
97
+
98
+ ----
99
+
100
+ -------------
101
+ Examples:
102
+ -------------
103
+
104
+ ****************
105
+ Basic Usage:
106
+ ****************
107
+
108
+ .. code:: python
109
+
110
+ from xvfbwrapper import Xvfb
111
+
112
+ vdisplay = Xvfb()
113
+ vdisplay.start()
114
+
115
+ try:
116
+ # launch stuff inside virtual display here.
117
+ finally:
118
+ # always either wrap your usage of Xvfb() with try / finally,
119
+ # or alternatively use Xvfb as a context manager.
120
+ # If you don't, you'll probably end up with a bunch of junk in /tmp
121
+ vdisplay.stop()
122
+
123
+ ----
124
+
125
+ *********************************************
126
+ Basic Usage, specifying display geometry:
127
+ *********************************************
128
+
129
+ .. code:: python
130
+
131
+ from xvfbwrapper import Xvfb
132
+
133
+ vdisplay = Xvfb(width=1280, height=740)
134
+ vdisplay.start()
135
+
136
+ try:
137
+ # launch stuff inside virtual display here.
138
+ finally:
139
+ vdisplay.stop()
140
+
141
+ ----
142
+
143
+ *******************************************
144
+ Basic Usage, specifying display number:
145
+ *******************************************
146
+
147
+ .. code:: python
148
+
149
+ from xvfbwrapper import Xvfb
150
+
151
+ vdisplay = Xvfb(display=23)
152
+ vdisplay.start()
153
+ # Xvfb is started with display :23
154
+ # see vdisplay.new_display
155
+
156
+ ----
157
+
158
+ *******************************
159
+ Usage as a Context Manager:
160
+ *******************************
161
+
162
+ .. code:: python
163
+
164
+ from xvfbwrapper import Xvfb
165
+
166
+ with Xvfb() as xvfb:
167
+ # launch stuff inside virtual display here.
168
+ # Xvfb will stop when this block completes
169
+
170
+ ----
171
+
172
+ ********************************************************
173
+ Usage in Testing: Headless Selenium WebDriver Tests:
174
+ ********************************************************
175
+
176
+ This test class uses *selenium webdriver* and *xvfbwrapper* to run tests
177
+ on Chrome with a headless display.
178
+
179
+ .. code:: python
180
+
181
+ import unittest
182
+
183
+ from selenium import webdriver
184
+ from xvfbwrapper import Xvfb
185
+
186
+
187
+ class TestPages(unittest.TestCase):
188
+
189
+ def setUp(self):
190
+ self.xvfb = Xvfb(width=1280, height=720)
191
+ self.addCleanup(self.xvfb.stop)
192
+ self.xvfb.start()
193
+ self.browser = webdriver.Chrome()
194
+ self.addCleanup(self.browser.quit)
195
+
196
+ def testUbuntuHomepage(self):
197
+ self.browser.get('https://www.ubuntu.com')
198
+ self.assertIn('Ubuntu', self.browser.title)
199
+
200
+ def testGoogleHomepage(self):
201
+ self.browser.get('https://www.google.com')
202
+ self.assertIn('Google', self.browser.title)
203
+
204
+
205
+ if __name__ == '__main__':
206
+ unittest.main()
207
+
208
+ * virtual display is launched
209
+ * Chrome launches inside virtual display (headless)
210
+ * browser is not shown while tests are run
211
+ * conditions are asserted in each test case
212
+ * browser quits during cleanup
213
+ * virtual display stops during cleanup
214
+
215
+ *Look Ma', no browser!*
216
+
217
+ (You can also take screenshots inside the virtual display to help diagnose test failures)
218
+
219
+ ----
220
+
221
+ ***************************************
222
+ Usage with multi-threaded execution
223
+ ***************************************
224
+
225
+ To run several xvfb servers at the same time, you can use the environ keyword
226
+ when starting the Xvfb instances. This provides isolation between threads. Be
227
+ sure to use the environment dictionary you initialize Xvfb with in your
228
+ subsequent system calls. Also, if you wish to inherit your current environment
229
+ you must use the copy method of os.environ and not simply assign a new
230
+ variable to os.environ:
231
+
232
+ .. code:: python
233
+
234
+ from xvfbwrapper import Xvfb
235
+ import subprocess as sp
236
+ import os
237
+
238
+ isolated_environment = os.environ.copy()
239
+ xvfb = Xvfb(environ=isolated_environment)
240
+ xvfb.start()
241
+ sp.run(
242
+ "xterm & sleep 1; kill %1 ",
243
+ shell=True,
244
+ env=isolated_environment,
245
+ )
246
+ xvfb.stop()
247
+
248
+ ----
249
+
250
+ ----------------------------------------------------
251
+ xvfbwrapper Development: running the unit tests:
252
+ ----------------------------------------------------
253
+
254
+ To create a virtual env and install required testing libraries:
255
+
256
+ .. code:: bash
257
+
258
+ $ python -m venv venv
259
+ $ source ./venv/bin/activate
260
+ (venv)$ pip install -r requirements_test.txt
261
+
262
+ To run all tests, linting, and type checking across all
263
+ supported/installed Python environments:
264
+
265
+ .. code:: bash
266
+
267
+ (venv)$ tox
268
+
269
+ To run all tests in the default Python environment:
270
+
271
+ .. code:: bash
272
+
273
+ (venv)$ pytest
@@ -0,0 +1,6 @@
1
+ xvfbwrapper.py,sha256=o9h-9oAJ1YKeex0pcmMZpMfDgZIeTiKnF43z50kzCFQ,5805
2
+ xvfbwrapper-0.2.10.dist-info/LICENSE,sha256=q0UOp9shMIWanBjEZAQuqDMHoTlIXkK9_6xigJGZp_M,1076
3
+ xvfbwrapper-0.2.10.dist-info/METADATA,sha256=UX0LGCsmADH3zaNNV6Kes6qr9SXu5t2OvVKgLd2vgKY,6903
4
+ xvfbwrapper-0.2.10.dist-info/WHEEL,sha256=52BFRY2Up02UkjOa29eZOS2VxUrpPORXg1pkohGGUS8,91
5
+ xvfbwrapper-0.2.10.dist-info/top_level.txt,sha256=LAS6W1pYzXvAHmQ8-X5IVkjjtCrFgnkX11NNzKtmMOc,12
6
+ xvfbwrapper-0.2.10.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (76.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ xvfbwrapper
xvfbwrapper.py ADDED
@@ -0,0 +1,188 @@
1
+ #!/usr/bin/env python3
2
+ # Corey Goldberg, 2012-2025
3
+ # License: MIT
4
+
5
+
6
+ '''Run a headless display inside X virtual framebuffer (Xvfb)'''
7
+
8
+
9
+ import os
10
+ import platform
11
+ import subprocess
12
+ import tempfile
13
+ import time
14
+
15
+ try:
16
+ import fcntl
17
+ except ImportError:
18
+ system = platform.system()
19
+ raise EnvironmentError(f'xvfbwrapper is not supported on this platform: {system}')
20
+
21
+ from random import randint
22
+
23
+
24
+ class Xvfb:
25
+
26
+ # Maximum value to use for a display. 32-bit maxint is the
27
+ # highest Xvfb currently supports
28
+ MAX_DISPLAY = 2147483647
29
+
30
+ def __init__(
31
+ self,
32
+ width=800,
33
+ height=680,
34
+ colordepth=24,
35
+ tempdir=None,
36
+ display=None,
37
+ environ=None,
38
+ timeout=10,
39
+ **kwargs,
40
+ ):
41
+ self.width = width
42
+ self.height = height
43
+ self.colordepth = colordepth
44
+ self._tempdir = tempdir or tempfile.gettempdir()
45
+ self._timeout = timeout
46
+ self.new_display = display
47
+
48
+ if environ:
49
+ self.environ = environ
50
+ else:
51
+ self.environ = os.environ
52
+
53
+ if not self.xvfb_exists():
54
+ msg = 'Can not find Xvfb. Please install it and try again.'
55
+ raise EnvironmentError(msg)
56
+
57
+ self.xvfb_cmd = []
58
+ self.extra_xvfb_args = [
59
+ '-screen',
60
+ '0',
61
+ f'{self.width}x{self.height}x{self.colordepth}',
62
+ ]
63
+
64
+ for key, value in kwargs.items():
65
+ self.extra_xvfb_args += [f'-{key}', value]
66
+
67
+ if 'DISPLAY' in self.environ:
68
+ self.orig_display_var = self.environ['DISPLAY']
69
+ else:
70
+ self.orig_display_var = None
71
+
72
+ self.proc = None
73
+
74
+ def __enter__(self):
75
+ # type: (...) -> Xvfb
76
+ self.start()
77
+ return self
78
+
79
+ def __exit__(self, exc_type, exc_val, exc_tb):
80
+ self.stop()
81
+
82
+ def start(self):
83
+ if self.new_display is not None:
84
+ if not self._get_lock_for_display(self.new_display):
85
+ raise ValueError(f'Could not lock display :{self.new_display}')
86
+ else:
87
+ self.new_display = self._get_next_unused_display()
88
+ display_var = f':{self.new_display}'
89
+ self.xvfb_cmd = ['Xvfb', display_var] + self.extra_xvfb_args
90
+ self.proc = subprocess.Popen(
91
+ self.xvfb_cmd,
92
+ stdout=subprocess.DEVNULL,
93
+ stderr=subprocess.DEVNULL,
94
+ close_fds=True,
95
+ )
96
+ start = time.time()
97
+ while not self._local_display_exists(self.new_display):
98
+ time.sleep(1e-3)
99
+ if time.time() - start > self._timeout:
100
+ self.stop()
101
+ raise RuntimeError(f'Xvfb display did not open: {self.xvfb_cmd}')
102
+ ret_code = self.proc.poll()
103
+ if ret_code is None:
104
+ self._set_display(display_var)
105
+ else:
106
+ self._cleanup_lock_file()
107
+ raise RuntimeError(f'Xvfb did not start ({ret_code}): {self.xvfb_cmd}')
108
+
109
+ def stop(self):
110
+ try:
111
+ if self.orig_display_var is None:
112
+ del self.environ['DISPLAY']
113
+ else:
114
+ self._set_display(self.orig_display_var)
115
+ if self.proc is not None:
116
+ try:
117
+ self.proc.terminate()
118
+ self.proc.wait(self._timeout)
119
+ except OSError:
120
+ pass
121
+ self.proc = None
122
+ finally:
123
+ self._cleanup_lock_file()
124
+
125
+ def xvfb_exists(self):
126
+ # type: (...) -> bool
127
+ '''Check that Xvfb is available on PATH and is executable.'''
128
+ paths = self.environ['PATH'].split(os.pathsep)
129
+ return any(os.access(os.path.join(path, 'Xvfb'), os.X_OK) for path in paths)
130
+
131
+ def _cleanup_lock_file(self):
132
+ '''
133
+ This should always get called if the process exits safely
134
+ with Xvfb.stop() (whether called explicitly, or by __exit__).
135
+
136
+ If you are ending up with /tmp/X123-lock files when Xvfb is not
137
+ running, then Xvfb is not exiting cleanly. Always either call
138
+ Xvfb.stop() in a finally block, or use Xvfb as a context manager
139
+ to ensure lock files are purged.
140
+
141
+ '''
142
+ self._lock_display_file.close()
143
+ try:
144
+ os.remove(self._lock_display_file.name)
145
+ except OSError:
146
+ pass
147
+
148
+ def _get_lock_for_display(self, display):
149
+ # type: (...) -> bool
150
+ '''
151
+ In order to ensure multi-process safety, this method attempts
152
+ to acquire an exclusive lock on a temporary file whose name
153
+ contains the display number for Xvfb.
154
+ '''
155
+ tempfile_path = os.path.join(self._tempdir, f'.X{display}-lock')
156
+ try:
157
+ self._lock_display_file = open(tempfile_path, 'w')
158
+ except PermissionError:
159
+ return False
160
+ else:
161
+ try:
162
+ fcntl.flock(self._lock_display_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
163
+ except BlockingIOError:
164
+ return False
165
+ else:
166
+ return True
167
+
168
+ def _get_next_unused_display(self):
169
+ # type: (...) -> int
170
+ '''
171
+ Randomly chooses a display number and tries to acquire a lock for this
172
+ number. If the lock could be acquired, returns this number, otherwise
173
+ choses a new one.
174
+ :return: free display number
175
+ '''
176
+ while True:
177
+ rand = randint(1, self.__class__.MAX_DISPLAY)
178
+ if self._get_lock_for_display(rand):
179
+ return rand
180
+ else:
181
+ continue
182
+
183
+ def _local_display_exists(self, display):
184
+ temp_display_file = os.path.join(self._tempdir, '.X11-unix', f'X{display}')
185
+ return os.path.exists(temp_display_file)
186
+
187
+ def _set_display(self, display_var):
188
+ self.environ['DISPLAY'] = display_var