git » libjio » commit 022433a

Remove Python 2 support

author Alberto Bertogli
2026-11-23 21:07:36 UTC
committer Alberto Bertogli
2026-11-23 21:11:05 UTC
parent c1b3140f9bfcf50f6b5afd20bbcf0ab3d7af8fe5

Remove Python 2 support

This patch removes Python 2 support, which reached EOL in 2020.

The Python bindings are simplified now that they can target Python 3,
and the Python scripts (from the tests) are updated to use Python 3.

INSTALL +2 -4
Makefile +3 -9
bindings/python/libjio.c +13 -129
bindings/python/setup.py +4 -9
tests/behaviour/runtests +4 -4
tests/behaviour/t_corruption.py +30 -29
tests/behaviour/t_fi.py +21 -21
tests/behaviour/t_normal.py +34 -34
tests/behaviour/tf.py +22 -14
tests/util/quick-test-run +16 -16
tests/util/wrap-python +12 -26

diff --git a/INSTALL b/INSTALL
index 08ac159..59c18a8 100644
--- a/INSTALL
+++ b/INSTALL
@@ -29,11 +29,9 @@ Special builds
 Python bindings
 ---------------
 
-The library comes with bindings for Python 2 and Python 3. In order to build
-them, you should have libjio already installed.
+The library comes with bindings for Python 3. In order to build them, you
+should have libjio already installed.
 
- - To build the Python 2 bindings, run "make python2". To install them, run
-   "make python2_install".
  - To build the Python 3 bindings, run "make python3". To install them, run
    "make python3_install".
 
diff --git a/Makefile b/Makefile
index 5e6a3f8..3dabd84 100644
--- a/Makefile
+++ b/Makefile
@@ -16,12 +16,6 @@ ifdef DEBUG
 	PY_DEBUG=--debug
 endif
 
-python2: libjio
-	cd bindings/python && python setup.py build $(PY_DEBUG)
-
-python2_install: python2
-	cd bindings/python && python setup.py install
-
 python3: libjio
 	cd bindings/python && python3 setup.py build $(PY_DEBUG)
 
@@ -35,10 +29,10 @@ preload:
 preload_install: preload
 	$(MAKE) -C bindings/preload/ install
 
-tests: all python2 python3
+tests: all python3
 	tests/util/quick-test-run normal
 
-tests-fi: all python2 python3
+tests-fi: all python3
 	@if [ "$(FI)" != "1" ]; then \
 		echo "Error: $@ has to be run using:  make FI=1 $@"; \
 		exit 1; \
@@ -52,7 +46,7 @@ clean:
 
 
 .PHONY: default all libjio install \
-	python2 python2_install python3 python3_install \
+	python3 python3_install \
 	preload preload_install \
 	tests tests-fi clean
 
diff --git a/bindings/python/libjio.c b/bindings/python/libjio.c
index f033dfb..317026a 100644
--- a/bindings/python/libjio.c
+++ b/bindings/python/libjio.c
@@ -1,6 +1,6 @@
 
 /*
- * Python (2 and 3) bindings for libjio
+ * Python 3 bindings for libjio
  * Alberto Bertogli (albertito@blitiri.com.ar)
  */
 
@@ -73,25 +73,6 @@ static void jf_dealloc(jfile_object *fp)
 }
 
 
-/* In order to support older Python versions, we use this function to convert
- * from ssize_t to a Python long. */
-PyObject *Our_PyLong_FromSsize_t(ssize_t v)
-{
-	/* Use PyLong_FromSsize_t() if available (Python 3 and >= 2.6),
-	 * otherwise just fall back to the function that fits the size. */
-#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 6)
-	return PyLong_FromSsize_t(v);
-#else
-	switch (sizeof(ssize_t)) {
-		case sizeof(long long):
-			return PyLong_FromLongLong(v);
-		default:
-			return PyLong_FromLong(v);
-	}
-#endif
-}
-
-
 /* fileno */
 PyDoc_STRVAR(jf_fileno__doc,
 "fileno()\n\
@@ -139,11 +120,7 @@ static PyObject *jf_read(jfile_object *fp, PyObject *args)
 	if (rv < 0) {
 		r = PyErr_SetFromErrno(PyExc_IOError);
 	} else {
-#ifdef PYTHON3
 		r = PyBytes_FromStringAndSize((char *) buf, rv);
-#elif PYTHON2
-		r = PyString_FromStringAndSize((char *) buf, rv);
-#endif
 	}
 
 	free(buf);
@@ -189,11 +166,7 @@ static PyObject *jf_pread(jfile_object *fp, PyObject *args)
 	if (rv < 0) {
 		r = PyErr_SetFromErrno(PyExc_IOError);
 	} else {
-#ifdef PYTHON3
 		r = PyBytes_FromStringAndSize((char *) buf, rv);
-#elif PYTHON2
-		r = PyString_FromStringAndSize((char *) buf, rv);
-#endif
 	}
 
 	free(buf);
@@ -207,13 +180,9 @@ PyDoc_STRVAR(jf_readv__doc,
 Reads the data from the file into the different buffers; returns the\n\
 number of bytes written.\n\
 The buffers must be objects that support slice assignment, like bytearray\n\
-(but *not* str).\n\
-Only available in Python >= 2.6.\n\
+(but *not* bytes).\n\
 It's a wrapper to jreadv().\n");
 
-/* readv requires the new Py_buffer interface, which is only available in
- * Python >= 2.6 */
-#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 6)
 static PyObject *jf_readv(jfile_object *fp, PyObject *args)
 {
 	ssize_t rv;
@@ -273,7 +242,7 @@ static PyObject *jf_readv(jfile_object *fp, PyObject *args)
 	if (rv < 0)
 		return PyErr_SetFromErrno(PyExc_IOError);
 
-	return Our_PyLong_FromSsize_t(rv);
+	return PyLong_FromSsize_t(rv);
 
 error:
 	/* We might get here with pos between 0 and len, so we must release
@@ -289,16 +258,6 @@ error:
 	return NULL;
 }
 
-#else
-
-static PyObject *jf_readv(jfile_object *fp, PyObject *args)
-{
-	PyErr_SetString(PyExc_NotImplementedError,
-			"only supported in Python >= 2.6");
-	return NULL;
-}
-
-#endif /* python version >= 2.6 */
 
 /* write */
 PyDoc_STRVAR(jf_write__doc,
@@ -324,7 +283,7 @@ static PyObject *jf_write(jfile_object *fp, PyObject *args)
 	if (rv < 0)
 		return PyErr_SetFromErrno(PyExc_IOError);
 
-	return Our_PyLong_FromSsize_t(rv);
+	return PyLong_FromSsize_t(rv);
 }
 
 /* pwrite */
@@ -357,7 +316,7 @@ static PyObject *jf_pwrite(jfile_object *fp, PyObject *args)
 	if (rv < 0)
 		return PyErr_SetFromErrno(PyExc_IOError);
 
-	return Our_PyLong_FromSsize_t(rv);
+	return PyLong_FromSsize_t(rv);
 }
 
 /* writev */
@@ -411,7 +370,7 @@ static PyObject *jf_writev(jfile_object *fp, PyObject *args)
 	if (rv < 0)
 		return PyErr_SetFromErrno(PyExc_IOError);
 
-	return Our_PyLong_FromSsize_t(rv);
+	return PyLong_FromSsize_t(rv);
 }
 
 /* truncate */
@@ -587,11 +546,7 @@ static PyObject *jf_new_trans(jfile_object *fp, PyObject *args)
 	if (!PyArg_ParseTuple(args, "|I:new_trans", &flags))
 		return NULL;
 
-#ifdef PYTHON3
 	tp = (jtrans_object *) jtrans_type.tp_alloc(&jtrans_type, 0);
-#elif PYTHON2
-	tp = PyObject_New(jtrans_object, &jtrans_type);
-#endif
 	if (tp == NULL)
 		return NULL;
 
@@ -634,33 +589,14 @@ static PyMethodDef jfile_methods[] = {
 	{ NULL }
 };
 
-#ifdef PYTHON3
 static PyTypeObject jfile_type = {
-	PyObject_HEAD_INIT(NULL)
+	PyVarObject_HEAD_INIT(NULL, 0)
 	.tp_name = "libjio.jfile",
-	.tp_itemsize = sizeof(jfile_object),
+	.tp_basicsize = sizeof(jfile_object),
 	.tp_dealloc = (destructor) jf_dealloc,
 	.tp_methods = jfile_methods,
 };
 
-#elif PYTHON2
-static PyObject *jf_getattr(jfile_object *fp, char *name)
-{
-	return Py_FindMethod(jfile_methods, (PyObject *)fp, name);
-}
-
-static PyTypeObject jfile_type = {
-	PyObject_HEAD_INIT(NULL)
-	0,
-	"libjio.jfile",
-	sizeof(jfile_object),
-	0,
-	(destructor)jf_dealloc,
-	0,
-	(getattrfunc)jf_getattr,
-};
-
-#endif
 
 
 /*
@@ -725,12 +661,8 @@ transaction.\n\
 It's a wrapper to jtrans_add_r().\n\
 \n\
 The buffer must be objects that support slice assignment, like bytearray\n\
-(but *not* str).\n\
-Only available in Python >= 2.6.\n");
+(but *not* bytes).\n");
 
-/* add_r requires the new Py_buffer interface, which is only available in
- * Python >= 2.6 */
-#if PY_MAJOR_VERSION >= 3 || (PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION >= 6)
 static PyObject *jt_add_r(jtrans_object *tp, PyObject *args)
 {
 	int rv;
@@ -785,16 +717,6 @@ static PyObject *jt_add_r(jtrans_object *tp, PyObject *args)
 	return PyLong_FromLong(rv);
 }
 
-#else
-
-static PyObject *jt_add_r(jtrans_object *tp, PyObject *args)
-{
-	PyErr_SetString(PyExc_NotImplementedError,
-			"only supported in Python >= 2.6");
-	return NULL;
-}
-
-#endif /* python version >= 2.6 */
 
 
 /* commit */
@@ -818,7 +740,7 @@ static PyObject *jt_commit(jtrans_object *tp, PyObject *args)
 	if (rv < 0)
 		return PyErr_SetFromErrno(PyExc_IOError);
 
-	return Our_PyLong_FromSsize_t(rv);
+	return PyLong_FromSsize_t(rv);
 }
 
 /* rollback */
@@ -842,7 +764,7 @@ static PyObject *jt_rollback(jtrans_object *tp, PyObject *args)
 	if (rv < 0)
 		return PyErr_SetFromErrno(PyExc_IOError);
 
-	return Our_PyLong_FromSsize_t(rv);
+	return PyLong_FromSsize_t(rv);
 }
 
 /* method table */
@@ -854,33 +776,14 @@ static PyMethodDef jtrans_methods[] = {
 	{ NULL }
 };
 
-#ifdef PYTHON3
 static PyTypeObject jtrans_type = {
-	PyObject_HEAD_INIT(NULL)
+	PyVarObject_HEAD_INIT(NULL, 0)
 	.tp_name = "libjio.jtrans",
-	.tp_itemsize = sizeof(jtrans_object),
+	.tp_basicsize = sizeof(jtrans_object),
 	.tp_dealloc = (destructor) jt_dealloc,
 	.tp_methods = jtrans_methods,
 };
 
-#elif PYTHON2
-static PyObject *jt_getattr(jtrans_object *tp, char *name)
-{
-	return Py_FindMethod(jtrans_methods, (PyObject *)tp, name);
-}
-
-static PyTypeObject jtrans_type = {
-	PyObject_HEAD_INIT(NULL)
-	0,
-	"libjio.jtrans",
-	sizeof(jtrans_object),
-	0,
-	(destructor)jt_dealloc,
-	0,
-	(getattrfunc)jt_getattr,
-};
-
-#endif
 
 
 /*
@@ -912,11 +815,7 @@ static PyObject *jf_open(PyObject *self, PyObject *args)
 				&jflags))
 		return NULL;
 
-#ifdef PYTHON3
 	fp = (jfile_object *) jfile_type.tp_alloc(&jfile_type, 0);
-#elif PYTHON2
-	fp = PyObject_New(jfile_object, &jfile_type);
-#endif
 
 	if (fp == NULL)
 		return NULL;
@@ -1049,7 +948,6 @@ static void populate_module(PyObject *m)
 }
 
 
-#ifdef PYTHON3
 static PyModuleDef libjio_module = {
 	PyModuleDef_HEAD_INIT,
 	.m_name = "libjio",
@@ -1073,19 +971,5 @@ PyMODINIT_FUNC PyInit_libjio(void)
 	return m;
 }
 
-#elif PYTHON2
-PyMODINIT_FUNC initlibjio(void)
-{
-	PyObject* m;
-
-	jfile_type.ob_type = &PyType_Type;
-	jtrans_type.ob_type = &PyType_Type;
-
-	m = Py_InitModule3("libjio", module_methods, module_doc);
-
-	populate_module(m);
-}
-
-#endif
 
 
diff --git a/bindings/python/setup.py b/bindings/python/setup.py
index b77fc89..54e2f55 100644
--- a/bindings/python/setup.py
+++ b/bindings/python/setup.py
@@ -1,16 +1,12 @@
 
-import sys
-from distutils.core import setup, Extension
-
-if sys.version_info[0] == 2:
-	ver_define = ('PYTHON2', '1')
-elif sys.version_info[0] == 3:
-	ver_define = ('PYTHON3', '1')
+try:
+	from setuptools import setup, Extension
+except ImportError:
+	from distutils.core import setup, Extension
 
 libjio = Extension("libjio",
 		libraries = ['jio'],
 		sources = ['libjio.c'],
-		define_macros = [ver_define],
 
 		# these two allow us to build without having libjio installed,
 		# assuming we're in the libjio source tree
@@ -31,7 +27,6 @@ setup(
 		"Operating System :: POSIX",
 		"Programming Language :: C",
 		"Programming Language :: Python",
-		"Programming Language :: Python :: 2",
 		"Programming Language :: Python :: 3",
 		"Topic :: Software Development",
 		"Topic :: Software Development :: Libraries",
diff --git a/tests/behaviour/runtests b/tests/behaviour/runtests
index a078083..5a29b77 100755
--- a/tests/behaviour/runtests
+++ b/tests/behaviour/runtests
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 import sys
 import resource
@@ -6,8 +6,8 @@ import tf
 
 possible_tests = ('normal', 'corruption', 'fi')
 if len(sys.argv) < 2 or sys.argv[1] not in possible_tests + ('all',):
-	print 'Usage: runtests', '|'.join(possible_tests + ('all',)),
-	print '[test_name]'
+	print('Usage: runtests', '|'.join(possible_tests + ('all',)),
+		'[test_name]')
 	sys.exit(1)
 
 if sys.argv[1] == 'all':
@@ -25,6 +25,6 @@ resource.setrlimit(resource.RLIMIT_FSIZE, (100 * M, 100 * M))
 resource.setrlimit(resource.RLIMIT_AS, (500 * M, 500 * M))
 
 for mn in mnames:
-	print '--', mn
+	print('--', mn)
 	tf.autorun(__import__(mn), specific_test)
 
diff --git a/tests/behaviour/t_corruption.py b/tests/behaviour/t_corruption.py
index 0a9d270..fa7c76d 100644
--- a/tests/behaviour/t_corruption.py
+++ b/tests/behaviour/t_corruption.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # Corruption tests using libfiu. libjio must have been built with libfiu
 # enabled (using something like make FI=1) for them to work.
@@ -8,11 +8,11 @@ from tf import *
 try:
 	import fiu
 except ImportError:
-	print
-	print "Error: unable to load fiu module. Corruption tests need"
-	print "libfiu support. Please install libfiu and recompile libjio"
-	print "with FI=1. You can still run the other tests."
-	print
+	print()
+	print("Error: unable to load fiu module. Corruption tests need")
+	print("libfiu support. Please install libfiu and recompile libjio")
+	print("with FI=1. You can still run the other tests.")
+	print()
 	raise
 
 
@@ -25,16 +25,15 @@ def test_c01():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
-	tc = open(transpath(n, 1)).read()
+	assert content(n) == b''
+	tc = content(transpath(n, 1))
 	# flip just one bit in the transaction data
-	pos = DHS + DOHS + len(c) / 2
-	tc = tc[:pos] + \
-		chr((ord(tc[pos]) & 0xFE) | (~ ord(tc[pos]) & 0x1) & 0xFF) + \
-		tc[pos + 1:]
-	open(transpath(n, 1), 'w').write(tc)
+	pos = DHS + DOHS + len(c) // 2
+	tc = tc[:pos] + bytes([tc[pos] ^ 0x1]) + tc[pos + 1:]
+	with open(transpath(n, 1), 'wb') as f:
+		f.write(tc)
 	fsck_verify(n, corrupt = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_c02():
@@ -46,11 +45,12 @@ def test_c02():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 	tp = transpath(n, 1)
-	open(tp, 'r+').truncate(len(content(tp)) - 2)
+	with open(tp, 'r+') as f:
+		f.truncate(len(content(tp)) - 2)
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_c03():
@@ -62,13 +62,13 @@ def test_c03():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 
 	tf = TransFile(transpath(n, 1))
 	tf.ops[0].tlen = 99
 	tf.save()
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_c04():
@@ -80,13 +80,13 @@ def test_c04():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 
 	tf = TransFile(transpath(n, 1))
 	tf.ops[0].tlen = 10
 	tf.save()
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_c05():
@@ -98,11 +98,12 @@ def test_c05():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 	tp = transpath(n, 1)
-	open(tp, 'r+').truncate(2)
+	with open(tp, 'r+') as f:
+		f.truncate(2)
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_c06():
@@ -114,7 +115,7 @@ def test_c06():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 
 	# there is no need to recalculate the checsum because it is verified
 	# after the version check
@@ -122,7 +123,7 @@ def test_c06():
 	tf.ver = 8
 	tf.save()
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_c07():
@@ -134,7 +135,7 @@ def test_c07():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 
 	# there is no need to recalculate the checsum because it is verified
 	# after the numops check
@@ -142,7 +143,7 @@ def test_c07():
 	tf.numops = 55
 	tf.save()
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_c08():
@@ -158,7 +159,7 @@ def test_c08():
 
 	run_forked(f1, f, jf)
 
-	assert content(n) == ''
+	assert content(n) == b''
 	open(jiodir(n) + '/broken', 'w+')
 
 	def f2(f, jf):
diff --git a/tests/behaviour/t_fi.py b/tests/behaviour/t_fi.py
index 419030d..4370485 100644
--- a/tests/behaviour/t_fi.py
+++ b/tests/behaviour/t_fi.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # General tests using libfiu. libjio must have been built with libfiu enabled
 # (using something like make FI=1) for them to work.
@@ -10,11 +10,11 @@ import libjio
 try:
 	import fiu
 except ImportError:
-	print
-	print "Error: unable to load fiu module. Fault injection tests need"
-	print "libfiu support. Please install libfiu and recompile libjio"
-	print "with FI=1. You can still run the other tests."
-	print
+	print()
+	print("Error: unable to load fiu module. Fault injection tests need")
+	print("libfiu support. Please install libfiu and recompile libjio")
+	print("with FI=1. You can still run the other tests.")
+	print()
 	raise
 
 
@@ -47,7 +47,7 @@ def test_f02():
 
 	n = run_with_tmp(f1)
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_f03():
@@ -59,9 +59,9 @@ def test_f03():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_f04():
@@ -79,9 +79,9 @@ def test_f04():
 	n = run_with_tmp(f1)
 
 	assert len(content(transpath(n, 1))) == DHS + DOHS + len(c)
-	assert content(n) == ''
+	assert content(n) == b''
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_f05():
@@ -99,9 +99,9 @@ def test_f05():
 	n = run_with_tmp(f1)
 
 	assert len(content(transpath(n, 1))) == DHS + (DOHS + len(c)) * 2
-	assert content(n) == ''
+	assert content(n) == b''
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_f06():
@@ -118,9 +118,9 @@ def test_f06():
 	n = run_with_tmp(f1)
 
 	assert len(content(transpath(n, 1))) == DHS + (DOHS + len(c)) * 2
-	assert content(n) == ''
+	assert content(n) == b''
 	fsck_verify(n, broken = 1)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_f07():
@@ -132,7 +132,7 @@ def test_f07():
 		jf.write(c)
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 	fsck_verify(n, reapplied = 1)
 	assert content(n) == c
 	cleanup(n)
@@ -152,7 +152,7 @@ def test_f08():
 
 	assert content(n) == c
 	fsck_verify(n, reapplied = 1)
-	assert content(n) == c + '\0' * 200 + c
+	assert content(n) == c + b'\0' * 200 + c
 	cleanup(n)
 
 def test_f09():
@@ -190,19 +190,19 @@ def test_f11():
 	c = gencontent()
 
 	def f1(f, jf):
-		jf.write('x' * (80 + len(c)))
+		jf.write(b'x' * (80 + len(c)))
 		t = jf.new_trans()
 		t.add_w(c, 80)
 		t.commit()
-		assert content(f.name) == 'x' * 80 + c
+		assert content(f.name) == b'x' * 80 + c
 		fiu.enable("jio/commit/tf_sync")
 		t.rollback()
 
 	n = run_with_tmp(f1)
 
-	assert content(n) == 'x' * 80 + c
+	assert content(n) == b'x' * 80 + c
 	fsck_verify(n, reapplied = 1)
-	assert content(n) == 'x' * (80 + len(c))
+	assert content(n) == b'x' * (80 + len(c))
 	cleanup(n)
 
 def test_f12():
diff --git a/tests/behaviour/t_normal.py b/tests/behaviour/t_normal.py
index efa70a1..8f7dd20 100644
--- a/tests/behaviour/t_normal.py
+++ b/tests/behaviour/t_normal.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # Normal tests.
 
@@ -12,9 +12,9 @@ def test_n01():
 		pass
 
 	n = run_with_tmp(f1)
-	assert content(n) == ''
+	assert content(n) == b''
 	fsck_verify(n)
-	assert content(n) == ''
+	assert content(n) == b''
 	cleanup(n)
 
 def test_n02():
@@ -22,8 +22,8 @@ def test_n02():
 	c = gencontent()
 
 	def f1(f, jf):
-		jf.write(c[:len(c) / 2])
-		jf.write(c[len(c) / 2:])
+		jf.write(c[:len(c) // 2])
+		jf.write(c[len(c) // 2:])
 		jf.lseek(0, 0)
 		assert jf.read(len(c) * 2) == c
 
@@ -40,7 +40,7 @@ def test_n03():
 		jf.pwrite(c, 80)
 
 	n = run_with_tmp(f1)
-	assert content(n) == '\0' * 80 + c
+	assert content(n) == b'\0' * 80 + c
 	fsck_verify(n)
 	cleanup(n)
 
@@ -50,7 +50,7 @@ def test_n04():
 		jf.truncate(826)
 
 	n = run_with_tmp(f1)
-	assert content(n) == '\0' * 826
+	assert content(n) == b'\0' * 826
 	fsck_verify(n)
 	cleanup(n)
 
@@ -64,7 +64,7 @@ def test_n05():
 		t.commit()
 
 	n = run_with_tmp(f1)
-	assert content(n) == '\0' * 80 + c
+	assert content(n) == b'\0' * 80 + c
 	fsck_verify(n)
 	cleanup(n)
 
@@ -83,7 +83,7 @@ def test_n06():
 	# XXX: This is weird, because the file was empty at the beginning.
 	# However, making it go back to 0 is delicate and the current code
 	# doesn't implement it. It probably should.
-	assert content(n) == '\0' * 80
+	assert content(n) == b'\0' * 80
 	fsck_verify(n)
 	cleanup(n)
 
@@ -197,9 +197,9 @@ def test_n13():
 	n = f.name
 	p = tmppath()
 
-	jf.write('x')
+	jf.write(b'x')
 	jf.jmove_journal(p)
-	jf.write('y')
+	jf.write(b'y')
 	del jf
 
 	assert libjio.jfsck(n, p)['total'] == 0
@@ -211,8 +211,8 @@ def test_n14():
 	n = f.name
 
 	jf.autosync_start(1, 10)
-	jf.write('x' * 200)
-	jf.write('x' * 200)
+	jf.write(b'x' * 200)
+	jf.write(b'x' * 200)
 	jf.autosync_stop()
 	del jf
 
@@ -227,7 +227,7 @@ def test_n15():
 	n = f.name
 
 	jf.pwrite(c, 2000)
-	assert content(n) == '\0' * 2000 + c
+	assert content(n) == b'\0' * 2000 + c
 	assert jf.pread(len(c), 2000) == c
 	del jf
 
@@ -272,9 +272,9 @@ def test_n17():
 	os.mkdir(p)
 	open(p + '/x', 'w')
 
-	jf.write('x')
+	jf.write(b'x')
 	jf.jmove_journal(p)
-	jf.write('y')
+	jf.write(b'y')
 	del jf
 	os.unlink(p + '/x')
 
@@ -297,7 +297,7 @@ def test_n18():
 	else:
 		raise AssertionError
 
-	assert content(n) == '\0' * 80 + c
+	assert content(n) == b'\0' * 80 + c
 	fsck_verify(n)
 	cleanup(n)
 
@@ -323,7 +323,7 @@ def test_n20():
 	t = jf.new_trans()
 
 	try:
-		t.add_w('', 80)
+		t.add_w(b'', 80)
 	except IOError:
 		pass
 	else:
@@ -339,13 +339,13 @@ def test_n21():
 	f, jf = bitmp()
 	n = f.name
 
-	jf.writev(["hello ", "world"])
-	l = [bytearray("......"), bytearray(".....")]
+	jf.writev([b"hello ", b"world"])
+	l = [bytearray(b"......"), bytearray(b".....")]
 	jf.lseek(0, 0)
 	jf.readv(l)
 
-	assert content(n) == "hello world"
-	assert l[0] == "hello " and l[1] == "world"
+	assert content(n) == b"hello world"
+	assert l[0] == b"hello " and l[1] == b"world"
 	fsck_verify(n)
 	cleanup(n)
 
@@ -357,7 +357,7 @@ def test_n22():
 	n = f.name
 
 	jf.pwrite(c, 2000)
-	assert content(n) == '\0' * 2000 + c
+	assert content(n) == b'\0' * 2000 + c
 	assert jf.pread(len(c), 2000) == c
 	del jf
 
@@ -380,13 +380,13 @@ def test_n23():
 	t.add_w(c1, 0)
 	t.add_r(buf1, 0)
 	t.add_w(c2, len(c1))
-	t.add_r(buf2, len(c1) - len(buf2) / 2)
+	t.add_r(buf2, len(c1) - len(buf2) // 2)
 	t.add_w(c3, len(c1) + len(c2))
 	t.commit()
 
 	assert content(n) == c1 + c2 + c3
 	assert buf1 == c1[:len(buf1)]
-	assert buf2 == c1[-(len(buf2) / 2):] + c2[:len(buf2) / 2]
+	assert buf2 == c1[-(len(buf2) // 2):] + c2[:len(buf2) // 2]
 
 	del t
 	del jf
@@ -414,15 +414,15 @@ def test_n24():
 		bufs.append((buf1, buf2))
 
 		# We can't use the bytearray directly because add_w requires
-		# an immutable object, so we convert it to a string
-		c1 = str(bytearray(i for _ in range(len_c1)))
-		c2 = str(bytearray(i for _ in range(len_c2)))
-		c3 = str(bytearray(i for _ in range(len_c3)))
+		# an immutable object, so we convert it to bytes
+		c1 = bytes(bytearray(i for _ in range(len_c1)))
+		c2 = bytes(bytearray(i for _ in range(len_c2)))
+		c3 = bytes(bytearray(i for _ in range(len_c3)))
 
 		t.add_w(c1, offset)
 		t.add_r(buf1, offset)
 		t.add_w(c2, offset + len(c1))
-		t.add_r(buf2, offset + len(c1) - len(buf2) / 2)
+		t.add_r(buf2, offset + len(c1) - len(buf2) // 2)
 		t.add_w(c3, offset + len(c1) + len(c2))
 
 	t.commit()
@@ -431,13 +431,13 @@ def test_n24():
 	for i in range(50):
 		offset = i * block_len
 		buf1, buf2 = bufs[i]
-		c1 = str(bytearray(i for _ in range(len_c1)))
-		c2 = str(bytearray(i for _ in range(len_c2)))
-		c3 = str(bytearray(i for _ in range(len_c3)))
+		c1 = bytes(bytearray(i for _ in range(len_c1)))
+		c2 = bytes(bytearray(i for _ in range(len_c2)))
+		c3 = bytes(bytearray(i for _ in range(len_c3)))
 
 		assert cont[offset : offset + block_len] == c1 + c2 + c3
 		assert buf1 == c1[:len(buf1)]
-		assert buf2 == c1[-(len(buf2) / 2):] + c2[:len(buf2) / 2]
+		assert buf2 == c1[-(len(buf2) // 2):] + c2[:len(buf2) // 2]
 
 	del t
 	del jf
diff --git a/tests/behaviour/tf.py b/tests/behaviour/tf.py
index 2f3f55c..d125d8c 100644
--- a/tests/behaviour/tf.py
+++ b/tests/behaviour/tf.py
@@ -28,12 +28,19 @@ def tmppath():
 	print a warning, or os.tmpfile() if it allowed us to get its name.
 	Since we just need a stupid name, we got our own function. Truly a
 	shame. Yes, it's not safe; I know and I don't care."""
+	global _tmppath_count
+	_tmppath_count += 1
 	tmpdir = os.environ.get('TMPDIR', '/tmp')
 	now = time.time()
 	now_s = str(int(now))
 	now_f = str((now - int(now)) * 10000)
 	now_str = "%s.%s" % (now_s[-5:], now_f[:now_f.find('.')])
-	return tmpdir + '/jiotest.%s.%s' % (now_str, os.getpid())
+	# The counter avoids collisions between calls made very close
+	# together, which are below the resolution of the timestamp.
+	return tmpdir + '/jiotest.%s.%s.%d' % (now_str, os.getpid(),
+			_tmppath_count)
+
+_tmppath_count = 0
 
 
 def run_forked(f, *args, **kwargs):
@@ -48,7 +55,7 @@ def run_forked(f, *args, **kwargs):
 		# parent
 		id, status = os.waitpid(pid, 0)
 		if not os.WIFEXITED(status):
-			raise RuntimeError, (id, status)
+			raise RuntimeError(id, status)
 
 def forked(f):
 	"Decorator that makes the function run in a different process."
@@ -59,8 +66,8 @@ def forked(f):
 
 def gencontent(size = 9377):
 	"Generates random content."
-	s = ''
-	a = "%.20f" % random.random()
+	s = b''
+	a = ("%.20f" % random.random()).encode('ascii')
 	while len(s) < size:
 		s += a
 	s = s[:size]
@@ -68,8 +75,8 @@ def gencontent(size = 9377):
 
 def content(path):
 	"Returns the content of the given path."
-	f = open(path)
-	return f.read()
+	with open(path, 'rb') as f:
+		return f.read()
 
 
 def biopen(path, mode = 'w+', jflags = 0):
@@ -87,7 +94,7 @@ def biopen(path, mode = 'w+', jflags = 0):
 	else:
 		raise RuntimeError
 
-	return open(path, mode), libjio.open(path, flags, 0400, jflags)
+	return open(path, mode), libjio.open(path, flags, 0o400, jflags)
 
 def bitmp(mode = 'w+', jflags = 0):
 	"Opens a temporary file with biopen()."
@@ -134,10 +141,10 @@ def fsck_verify(n, **kwargs):
 
 	for k in expected:
 		if k not in res:
-			raise AssertionError, k + ' not in res'
+			raise AssertionError(k + ' not in res')
 		if res[k] != expected[k]:
-			raise AssertionError, k + ' does not match: ' + \
-					str(res)
+			raise AssertionError(k + ' does not match: ' +
+					str(res))
 
 def cleanup(path):
 	"""Unlinks the path and its temporary libjio directory. The libjio
@@ -173,7 +180,7 @@ class TransFile (object):
 			self.load()
 
 	def load(self):
-		fd = open(self.path)
+		fd = open(self.path, 'rb')
 
 		# header
 		hdrfmt = "!HHI"
@@ -202,13 +209,14 @@ class TransFile (object):
 		# the lack of integrity checking in this function is
 		# intentional, so we can write broken transactions and see how
 		# jfsck() copes with them
-		fd = open(self.path, 'w')
+		fd = open(self.path, 'wb')
 		fd.write(struct.pack("!HHI", self.ver, self.flags, self.id))
 		for o in self.ops:
 			fd.write(struct.pack("!IQ", o.tlen, o.offset,))
 			fd.write(o.payload)
 		fd.write(struct.pack("!IQ", 0, 0))
 		fd.write(struct.pack("!II", self.numops, self.checksum))
+		fd.close()
 
 	def __repr__(self):
 		return '<TransFile %s: id:%d f:%s n:%d ops:%s>' % \
@@ -224,7 +232,7 @@ def gen_ret_seq(seq):
 	last = [0]
 	def newf(*args, **kwargs):
 		try:
-			r = it.next()
+			r = next(it)
 			last[0] = r
 			return r
 		except StopIteration:
@@ -249,7 +257,7 @@ def autorun(module, specific_test = None):
 			desc = ''
 			if obj.__doc__:
 				desc = obj.__doc__
-			print "%-10s %-60.60s" % (name, desc)
+			print("%-10s %-60.60s" % (name, desc))
 			obj()
 
 
diff --git a/tests/util/quick-test-run b/tests/util/quick-test-run
index 87061d5..203d2bc 100755
--- a/tests/util/quick-test-run
+++ b/tests/util/quick-test-run
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # This is a convenience script for running some of the other tests without
 # manual intervention, as a means of a fast and easy correctness test.
@@ -17,12 +17,12 @@ import random
 os.chdir(os.path.dirname(sys.argv[0]))
 
 if len(sys.argv) != 2 or sys.argv[1] not in ("normal", "fiu"):
-	sys.stderr.write("Usage: %s [normal|fiu]" %
+	sys.stderr.write("Usage: %s [normal|fiu]\n" %
 				os.path.basename(sys.argv[0]))
 	sys.exit(1)
 
 def run_behaviour_tests(test_type):
-	ret = subprocess.call(["./wrap-python", "2", "../behaviour/runtests",
+	ret = subprocess.call(["./wrap-python", "../behaviour/runtests",
 				test_type])
 	if ret != 0:
 		sys.exit(ret)
@@ -36,7 +36,7 @@ def run_stress_tests(nops = 0, nprocs = 0, fi = False, fsize = 20):
 			os.getpid(),
 			random.randint(0, 1000000000))
 
-	args = ["./wrap-python", "3", "../stress/jiostress",
+	args = ["./wrap-python", "../stress/jiostress",
 			tmp_path, str(fsize)]
 	if nops:
 		args += ["-n", str(nops)]
@@ -50,23 +50,23 @@ def run_stress_tests(nops = 0, nprocs = 0, fi = False, fsize = 20):
 		sys.exit(ret)
 
 if sys.argv[1] == "normal":
-	print "behaviour tests (normal)"
+	print("behaviour tests (normal)")
 	run_behaviour_tests("normal")
-	print
-	print "stress tests (normal)"
+	print()
+	print("stress tests (normal)")
 	run_stress_tests(nops = 50, nprocs = 3)
 else:
-	print "behaviour tests (all)"
+	print("behaviour tests (all)")
 	run_behaviour_tests("all")
-	print
-	print "stress tests (normal)"
+	print()
+	print("stress tests (normal)")
 	run_stress_tests(nops = 50, nprocs = 3)
-	print
-	print "stress tests (fiu)"
+	print()
+	print("stress tests (fiu)")
 	run_stress_tests(nops = 400, fi = True)
 
-print
-print
-print "Tests completed successfuly"
-print
+print()
+print()
+print("Tests completed successfuly")
+print()
 
diff --git a/tests/util/wrap-python b/tests/util/wrap-python
index 629a45b..804e5bf 100755
--- a/tests/util/wrap-python
+++ b/tests/util/wrap-python
@@ -1,23 +1,13 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
 
 # Python wrapper, which makes it able to import the built (and not the
 # installed) version of libjio.
-#
-# The first parameter must be the python version (2 or 3)
 
 import sys
 import os
 import glob
 
 
-if len(sys.argv) < 2 or sys.argv[1] not in ("2", "3"):
-	sys.stderr.write("Error: the first argument must be the " +
-				"version (2 or 3)\n")
-	sys.exit(1)
-
-py_ver = sys.argv[1]
-
-
 # Find the path where the library was built and add it to the lookup paths, so
 # we run against it
 lib_bin = os.path.dirname(sys.argv[0]) + "/../../libjio/build/libjio.so"
@@ -31,29 +21,25 @@ os.environ["LD_LIBRARY_PATH"] = ":".join([lib_path, \
 				os.environ.get("LD_LIBRARY_PATH", "")])
 
 
-# Find out the corresponding module path for the desired python version. The
-# path must be absolute
-mod_bins = glob.glob(os.path.dirname(sys.argv[0]) +
-			"/../../bindings/python/build/lib*-%s.*/libjio*.so" \
-				% py_ver)
+# Find out the module path. The path must be absolute.
+# Older setuptools/distutils name the directory "lib.<plat>-3.X", newer
+# versions use "lib.<plat>-cpython-3X".
+mod_bins = []
+for pattern in ("lib*-3.*", "lib*-cpython-3*"):
+	mod_bins += glob.glob(os.path.dirname(sys.argv[0]) +
+			"/../../bindings/python/build/" + pattern +
+			"/libjio*.so")
 if not mod_bins:
-	sys.stderr.write(("Can't find python%s bindings, run " +
-				"make python%s\n") % (py_ver, py_ver))
+	sys.stderr.write("Can't find python bindings, run make python3\n")
 	sys.exit(1)
 
 if len(mod_bins) > 1:
-	sys.stderr.write("Found too many matching python%s bindings" \
-				% py_ver)
+	sys.stderr.write("Found too many matching python bindings\n")
 	sys.exit(1)
 
 mod_path = os.path.dirname(os.path.abspath(mod_bins[0]))
 os.environ["PYTHONPATH"] = ":".join([mod_path,
 					os.environ.get("PYTHONPATH", "")])
 
-if py_ver == '2':
-	py_bin = "python"
-else:
-	py_bin = "python3"
-
-os.execvp(py_bin, [py_bin] + sys.argv[2:])
+os.execvp("python3", ["python3"] + sys.argv[1:])