Port autopkgtests to python3, taken from Ubuntu, thanks to them and Dimitri John Ledkov (Closes: #937169)

This commit is contained in:
Laurent Bigonville 2020-01-30 00:58:18 +01:00
parent 5c60ced7db
commit dcb5203681
5 changed files with 63 additions and 56 deletions

7
debian/changelog vendored
View File

@ -1,3 +1,10 @@
nut (2.7.4-12) unstable; urgency=medium
* Port autopkgtests to python3, taken from Ubuntu, thanks to them and
Dimitri John Ledkov (Closes: #937169)
-- Laurent Bigonville <bigon@debian.org> Thu, 30 Jan 2020 01:06:14 +0100
nut (2.7.4-11) unstable; urgency=medium
* Remove python(2) binding and disable nut-monitor package for now as it

View File

@ -1,3 +1,3 @@
Tests: nut
Depends: lsb-release, netcat, nut-client, nut-server, psmisc, python
Depends: lsb-release, netcat, nut-client, nut-server, psmisc, python3
Restrictions: needs-root

2
debian/tests/nut vendored
View File

@ -3,4 +3,4 @@
# Testing nut
#------------
set -e
python `dirname $0`/test-nut.py 2>&1
python3 `dirname $0`/test-nut.py 2>&1

View File

@ -75,7 +75,7 @@ try:
except ImportError:
class PrivateNutTest(object):
'''Empty class'''
print >>sys.stdout, "Skipping private tests"
print("Skipping private tests")
class NutTestCommon(testlib.TestlibCase):
@ -161,7 +161,7 @@ FINALDELAY 0
testlib.create_fill(self.notifyscript, '''
#! /bin/bash
echo "$*" > ''' + self.notifylog + '\n', mode=0755)
echo "$*" > ''' + self.notifylog + '\n', mode=0o755)
# dummy-ups absolutely needs a data file, even if empty
testlib.config_replace('/etc/nut/dummy.dev', '''
@ -230,7 +230,7 @@ UPSMON_OPTIONS=""
rc, report = testlib.cmd([self.initscript, 'start'])
expected = 0
result = 'Got exit code %d, expected %d\n' % (rc, expected)
self.assertEquals(expected, rc, result + report)
self.assertEqual(expected, rc, result + report)
time.sleep(2)
def _stop(self):
@ -238,14 +238,14 @@ UPSMON_OPTIONS=""
rc, report = testlib.cmd([self.initscript, 'stop'])
expected = 0
result = 'Got exit code %d, expected %d\n' % (rc, expected)
self.assertEquals(expected, rc, result + report)
self.assertEqual(expected, rc, result + report)
def _reload(self):
'''Reload NUT'''
rc, report = testlib.cmd([self.initscript, 'force-reload'])
expected = 0
result = 'Got exit code %d, expected %d\n' % (rc, expected)
self.assertEquals(expected, rc, result + report)
self.assertEqual(expected, rc, result + report)
def _restart(self):
'''Restart NUT'''
@ -261,7 +261,7 @@ UPSMON_OPTIONS=""
self._skipped("init script does not support status command")
expected = 1
result = 'Got exit code %d, expected %d\n' % (rc, expected)
self.assertEquals(expected, rc, result + report)
self.assertEqual(expected, rc, result + report)
def _testDaemons(self, daemons):
'''Daemons running'''
@ -379,7 +379,7 @@ printf '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\n' | nc -q 1 127.0.0.1
sleep 1
dd if=/dev/urandom count=64 | nc -q 1 127.0.0.1 3493
'''
testlib.create_fill(script, contents, mode=0755)
testlib.create_fill(script, contents, mode=0o755)
rc, report = testlib.cmd([script])
# It should not have crashed. Let's see if it did
@ -414,9 +414,9 @@ if __name__ == '__main__':
# suite.addTest(unittest.TestLoader().loadTestsFromTestCase(MyPrivateTest))
else:
print '''Usage:
print('''Usage:
test-nut.py [-v] basic tests
'''
''')
sys.exit(1)
rc = unittest.TextTestRunner(verbosity=2).run(suite)
if not rc.wasSuccessful():

View File

@ -22,7 +22,6 @@
import string, random, crypt, subprocess, pwd, grp, signal, time, unittest, tempfile, shutil, os, os.path, re, glob
import sys, socket, gzip
from stat import *
from encodings import string_escape
import warnings
warnings.filterwarnings('ignore', message=r'.*apt_pkg\.TagFile.*', category=DeprecationWarning)
@ -77,7 +76,7 @@ def _save_backup(path):
def config_copydir(path):
if os.path.exists(path) and not os.path.isdir(path):
raise OSError, "'%s' is not a directory" % (path)
raise OSError("'%s' is not a directory" % (path))
_restore_backup(path)
pathbackup = path + '.autotest'
@ -90,13 +89,13 @@ def config_replace(path,contents,append=False):
if os.path.exists(path):
_save_backup(path)
if append:
contents = file(path).read() + contents
contents = open(path).read() + contents
open(path, 'w').write(contents)
def config_comment(path, field):
_save_backup(path)
contents = ""
for line in file(path):
for line in open(path).readlines():
if re.search("^\s*%s\s*=" % (field), line):
line = "#" + line
contents += line
@ -112,7 +111,7 @@ def config_set(path, field, value, spaces=True):
else:
setting = '%s=%s\n' % (field, value)
found = False
for line in file(path):
for line in open(path).readlines():
if re.search("^\s*%s\s*=" % (field), line):
found = True
line = setting
@ -155,20 +154,20 @@ def timeout(secs, f, *args):
def require_nonroot():
if os.geteuid() == 0:
print >>sys.stderr, "This series of tests should be run as a regular user with sudo access, not as root."
print("This series of tests should be run as a regular user with sudo access, not as root.", file=sys.stderr)
sys.exit(1)
def require_root():
if os.geteuid() != 0:
print >>sys.stderr, "This series of tests should be run with root privileges (e.g. via sudo)."
print("This series of tests should be run with root privileges (e.g. via sudo).", file=sys.stderr)
sys.exit(1)
def require_sudo():
if os.geteuid() != 0 or os.environ.get('SUDO_USER', None) == None:
print >>sys.stderr, "This series of tests must be run under sudo."
print("This series of tests must be run under sudo.", file=sys.stderr)
sys.exit(1)
if os.environ['SUDO_USER'] == 'root':
print >>sys.stderr, 'Please run this test using sudo from a regular user. (You ran sudo from root.)'
print('Please run this test using sudo from a regular user. (You ran sudo from root.)', file=sys.stderr)
sys.exit(1)
def random_string(length,lower=False):
@ -190,14 +189,14 @@ def mkstemp_fill(contents,suffix='',prefix='testlib-',dir=None):
handle, name = tempfile.mkstemp(suffix=suffix,prefix=prefix,dir=dir)
os.close(handle)
handle = file(name,"w+")
handle = open(name,"w+")
handle.write(contents)
handle.flush()
handle.seek(0)
return handle, name
def create_fill(path, contents, mode=0644):
def create_fill(path, contents, mode=0o644):
'''Safely create a page'''
# make the temp file in the same dir as the destination file so we
# don't get invalid cross-device link errors when we rename
@ -342,7 +341,7 @@ def ubuntu_release():
return "UNKNOWN"
if size > 1024*1024:
raise IOError, 'Could not open "%s" (too big)' % f
raise IOError('Could not open "%s" (too big)' % f)
try:
fh = open("/etc/lsb-release", 'r')
@ -364,8 +363,8 @@ def cmd(command, input = None, stderr = subprocess.STDOUT, stdout = subprocess.P
a textual error if it failed.'''
try:
sp = subprocess.Popen(command, stdin=stdin, stdout=stdout, stderr=stderr, close_fds=True, preexec_fn=subprocess_setup)
except OSError, e:
sp = subprocess.Popen(command, stdin=stdin, stdout=stdout, stderr=stderr, close_fds=True, preexec_fn=subprocess_setup, universal_newlines=True)
except OSError as e:
return [127, str(e)]
out, outerr = sp.communicate(input)
@ -382,7 +381,7 @@ def cmd_pipe(command1, command2, input = None, stderr = subprocess.STDOUT, stdin
try:
sp1 = subprocess.Popen(command1, stdin=stdin, stdout=subprocess.PIPE, stderr=stderr, close_fds=True)
sp2 = subprocess.Popen(command2, stdin=sp1.stdout, stdout=subprocess.PIPE, stderr=stderr, close_fds=True)
except OSError, e:
except OSError as e:
return [127, str(e)]
out = sp2.communicate(input)[0]
@ -407,7 +406,7 @@ def cwd_has_enough_space(cdir, total_bytes):
cdir = os.getcwd()
while cdir != '/':
if not mounts.has_key(cdir):
if cdir not in mounts:
cdir = os.path.dirname(cdir)
continue
if kb < mounts[cdir]:
@ -650,7 +649,7 @@ def is_kdeinit_running():
# check for it.
rc, report = cmd(['ps', 'x'])
if 'kdeinit4 Running' not in report:
print >>sys.stderr, ("kdeinit not running (you may start/stop any KDE application then run this script again)")
print(("kdeinit not running (you may start/stop any KDE application then run this script again)"), file=sys.stderr)
return False
return True
@ -660,7 +659,7 @@ def get_pkgconfig_flags(libs=[]):
rc, pkg_config = cmd(['pkg-config', '--cflags', '--libs'] + libs)
expected = 0
if rc != expected:
print >>sys.stderr, 'Got exit code %d, expected %d\n' % (rc, expected)
print('Got exit code %d, expected %d\n' % (rc, expected), file=sys.stderr)
assert(rc == expected)
return pkg_config.split()
@ -750,8 +749,8 @@ class TestlibManager(object):
# Load LSB release file
self.lsb_release = dict()
if not os.path.exists('/usr/bin/lsb_release') and not os.path.exists('/bin/lsb_release'):
raise OSError, "Please install 'lsb-release'"
for line in subprocess.Popen(['lsb_release','-a'],stdout=subprocess.PIPE,stderr=subprocess.PIPE).communicate()[0].splitlines():
raise OSError("Please install 'lsb-release'")
for line in subprocess.Popen(['lsb_release','-a'],stdout=subprocess.PIPE,stderr=subprocess.PIPE, universal_newlines=True).communicate()[0].splitlines():
field, value = line.split(':',1)
value=value.strip()
field=field.strip()
@ -768,7 +767,7 @@ class TestlibManager(object):
self.lsb_release['Distributor ID'] = "Ubuntu"
self.lsb_release['Release'] = 8.04
else:
raise OSError, "Unknown version of HP MIE"
raise OSError("Unknown version of HP MIE")
# FIXME: hack to assume a most-recent release if we're not
# running under Ubuntu.
@ -789,7 +788,7 @@ class TestlibManager(object):
elif machine.startswith('arm'):
self.dpkg_arch = 'armel'
else:
raise ValueError, "Unknown machine type '%s'" % (machine)
raise ValueError("Unknown machine type '%s'" % (machine))
else:
self.dpkg_arch = cmd(['dpkg','--print-architecture'])[1].strip()
@ -800,7 +799,8 @@ class TestlibManager(object):
versig = '/proc/version_signature'
if os.path.exists(versig):
self.kernel_is_ubuntu = True
self.kernel_version_signature = file(versig).read().strip()
with open(versig) as f:
self.kernel_version_signature = f.read().strip()
self.kernel_version_ubuntu = self.kernel_version
elif os.path.exists('/usr/bin/dpkg'):
# this can easily be inaccurate but is only an issue for Dapper
@ -829,14 +829,14 @@ class TestlibManager(object):
kernel = self.kernel_version_ubuntu
if kernel != self.kernel_version_signature:
kernel += " (%s)" % (self.kernel_version_signature)
print >>sys.stdout, "Running test: '%s' distro: '%s %.2f' kernel: '%s' arch: '%s' uid: %d/%d SUDO_USER: '%s')" % ( \
print("Running test: '%s' distro: '%s %.2f' kernel: '%s' arch: '%s' uid: %d/%d SUDO_USER: '%s')" % ( \
sys.argv[0],
self.lsb_release['Distributor ID'],
self.lsb_release['Release'],
kernel,
self.dpkg_arch,
os.geteuid(), os.getuid(),
os.environ.get('SUDO_USER', ''))
os.environ.get('SUDO_USER', '')), file=sys.stdout)
sys.stdout.flush()
# Additional heuristics
@ -848,7 +848,7 @@ class TestlibManager(object):
# time.sleep(0.5)
def hello(self, msg):
print >>sys.stderr, "Hello from %s" % (msg)
print("Hello from %s" % (msg), file=sys.stderr)
# The central instance
manager = TestlibManager()
@ -885,11 +885,11 @@ class TestlibCase(unittest.TestCase):
if self.lsb_release['Release'] == 8.04 and rc == 255 and len(out) > 0:
rc = 0
result = 'Got exit code %d, expected %d:\n%s\n' % (rc, expected, report)
self.assertEquals(expected, rc, result)
self.assertEqual(expected, rc, result)
filetype = '^%s$' % (filetype)
result = 'File type reported by file: [%s], expected regex: [%s]\n' % (out, filetype)
self.assertNotEquals(None, re.search(filetype, out), result)
self.assertNotEqual(None, re.search(filetype, out), result)
def yank_commonname_from_cert(self, certfile):
'''Extract the commonName from a given PEM'''
@ -905,12 +905,12 @@ class TestlibCase(unittest.TestCase):
def announce(self, text):
if self.my_verbosity:
print >>sys.stdout, "(%s) " % (text),
print("(%s) " % (text), end=' ', file=sys.stdout)
sys.stdout.flush()
def make_clean(self):
rc, output = self.shell_cmd(['make','clean'])
self.assertEquals(rc, 0, output)
self.assertEqual(rc, 0, output)
def get_makefile_compiler(self):
# Find potential compiler name
@ -929,7 +929,7 @@ class TestlibCase(unittest.TestCase):
compiler = self.get_makefile_compiler()
rc, output = self.shell_cmd(['make',target])
self.assertEquals(rc, expected, 'rc(%d)!=%d:\n' % (rc, expected) + output)
self.assertEqual(rc, expected, 'rc(%d)!=%d:\n' % (rc, expected) + output)
self.assertTrue('%s ' % (compiler) in output, 'Expected "%s":' % (compiler) + output)
return output
@ -954,13 +954,13 @@ class TestlibCase(unittest.TestCase):
'''Test a shell command matches a specific exit code'''
rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr)
result = 'Got exit code %d, expected %d\n' % (rc, expected)
self.assertEquals(expected, rc, msg + result + report)
self.assertEqual(expected, rc, msg + result + report)
def assertShellExitNotEquals(self, unwanted, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg=""):
'''Test a shell command doesn't match a specific exit code'''
rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr)
result = 'Got (unwanted) exit code %d\n' % rc
self.assertNotEquals(unwanted, rc, msg + result + report)
self.assertNotEqual(unwanted, rc, msg + result + report)
def assertShellOutputContains(self, text, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg="", invert=False):
'''Test a shell command contains a specific output'''
@ -976,12 +976,12 @@ class TestlibCase(unittest.TestCase):
rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr)
result = 'Got exit code %d. Looking for exact text "%s" (%s)\n' % (rc, text, " ".join(args))
if not invert:
self.assertEquals(text, out, msg + result + report)
self.assertEqual(text, out, msg + result + report)
else:
self.assertNotEquals(text, out, msg + result + report)
self.assertNotEqual(text, out, msg + result + report)
if expected != None:
result = 'Got exit code %d. Expected %d (%s)\n' % (rc, expected, " ".join(args))
self.assertEquals(rc, expected, msg + result + report)
self.assertEqual(rc, expected, msg + result + report)
def _word_find(self, report, content, invert=False):
'''Check for a specific string'''
@ -994,20 +994,20 @@ class TestlibCase(unittest.TestCase):
def _test_sysctl_value(self, path, expected, msg=None, exists=True):
sysctl = '/proc/sys/%s' % (path)
self.assertEquals(exists, os.path.exists(sysctl), sysctl)
self.assertEqual(exists, os.path.exists(sysctl), sysctl)
value = None
if exists:
value = int(file(sysctl).read())
value = int(open(sysctl).read())
report = "%s is not %d: %d" % (sysctl, expected, value)
if msg:
report += " (%s)" % (msg)
self.assertEquals(value, expected, report)
self.assertEqual(value, expected, report)
return value
def set_sysctl_value(self, path, desired):
sysctl = '/proc/sys/%s' % (path)
self.assertTrue(os.path.exists(sysctl),"%s does not exist" % (sysctl))
file(sysctl,'w').write(str(desired))
open(sysctl,'w').write(str(desired))
self._test_sysctl_value(path, desired)
def kernel_at_least(self, introduced):
@ -1031,7 +1031,7 @@ class TestGroup:
self.group = None
if group:
if group_exists(group):
raise ValueError, 'group name already exists'
raise ValueError('group name already exists')
else:
while(True):
group = random_string(7,lower=lower)
@ -1063,11 +1063,11 @@ class TestUser:
self.login = None
if os.geteuid() != 0:
raise ValueError, "You must be root to run this test"
raise ValueError("You must be root to run this test")
if login:
if login_exists(login):
raise ValueError, 'login name already exists'
raise ValueError('login name already exists')
else:
while(True):
login = 't' + random_string(7,lower=lower)
@ -1114,7 +1114,7 @@ class TestUser:
'''Add user to the specified group name'''
rc, report = cmd(['usermod', '-G', group, self.login])
if rc != 0:
print report
print(report)
assert rc == 0
# Timeout handler using alarm() from John P. Speno's Pythonic Avocado
@ -1140,5 +1140,5 @@ class TimeoutFunction:
return result
def main():
print "hi"
print("hi")
unittest.main()