Commit 531b3dbb authored by Jérome Perrin's avatar Jérome Perrin

tests: support running tests with py.test

 - rename test files as test_*.py, this is how tests are collected by
   py.test

 - take into account that test runner might disable log level and patch
   sys.stdout already

/reviewed-on nexedi/slapos.core!92
parent 75a80515
...@@ -97,7 +97,8 @@ class TestCliProxyShow(CliMixin): ...@@ -97,7 +97,8 @@ class TestCliProxyShow(CliMixin):
self.conf.logger = self.logger self.conf.logger = self.logger
# load database # load database
schema = bytes2str(pkg_resources.resource_string('slapos.tests.slapproxy', 'database_dump_version_current.sql')) schema = bytes2str(pkg_resources.resource_string(
'slapos.tests.test_slapproxy', 'database_dump_version_current.sql'))
db = sqlite_connect(self.db_file.name) db = sqlite_connect(self.db_file.name)
db.cursor().executescript(schema) db.cursor().executescript(schema)
db.commit() db.commit()
...@@ -148,39 +149,32 @@ class TestCliProxyShow(CliMixin): ...@@ -148,39 +149,32 @@ class TestCliProxyShow(CliMixin):
self.logger.info.assert_not_called() self.logger.info.assert_not_called()
def test_proxy_show_displays_on_stdout(self): def test_proxy_show_displays_on_stdout(self):
saved_stderr = sys.stderr # we patch logging to make sure our messages are outputed, even with test
saved_stdout = sys.stdout # runners like pytest which allows disabling output
sys.stderr = stderr = StringIO() with patch.object(sys, 'stdout', StringIO()) as stdout, \
sys.stdout = stdout = StringIO() patch.object(sys, 'stderr', StringIO()) as stderr, \
try: patch('logging.Logger.isEnabledFor', returned_value=True):
do_show(self.conf) do_show(self.conf)
finally:
sys.stderr = saved_stderr
sys.stdout = saved_stdout
# 287375f0cba269902ba1bc50242839d7 is the hash of an installed software # 287375f0cba269902ba1bc50242839d7 is the hash of an installed software
# in our setup database # in our setup database
# pytest users, be sure to use --log-level=DEBUG
self.assertIn('287375f0cba269902ba1bc50242839d7', stdout.getvalue()) self.assertIn('287375f0cba269902ba1bc50242839d7', stdout.getvalue())
self.assertEqual('', stderr.getvalue()) self.assertEqual('', stderr.getvalue())
def test_proxy_show_use_pager(self): def test_proxy_show_use_pager(self):
saved_stderr = sys.stderr # we patch logging to make sure our messages are outputed, even with test
saved_stdout = sys.stdout # runners like pytest which allows disabling output
sys.stderr = stderr = StringIO() with patch.object(sys, 'stdout', StringIO()) as stdout, \
sys.stdout = stdout = StringIO() patch.object(sys, 'stderr', StringIO()) as stderr, \
stdout.isatty = lambda *args: True patch('logging.Logger.isEnabledFor', returned_value=True):
stdout.isatty = lambda *args: True
# use a pager that just output to a file.
tmp = tempfile.NamedTemporaryFile(delete=False) # use a pager that just output to a file.
self.addCleanup(os.unlink, tmp.name) tmp = tempfile.NamedTemporaryFile(delete=False)
os.environ['PAGER'] = 'cat > {}'.format(tmp.name) self.addCleanup(os.unlink, tmp.name)
os.environ['PAGER'] = 'cat > {}'.format(tmp.name)
try:
do_show(self.conf) do_show(self.conf)
finally:
sys.stderr = saved_stderr
sys.stdout = saved_stdout
self.assertEqual('', stdout.getvalue()) self.assertEqual('', stdout.getvalue())
self.assertEqual('', stderr.getvalue()) self.assertEqual('', stderr.getvalue())
......
...@@ -68,36 +68,40 @@ class SlapPopenTestCase(unittest.TestCase): ...@@ -68,36 +68,40 @@ class SlapPopenTestCase(unittest.TestCase):
self.script.write(b'#!/bin/sh\necho "exit code?"\nread rc\nexit $rc') self.script.write(b'#!/bin/sh\necho "exit code?"\nread rc\nexit $rc')
self.script.close() self.script.close()
# keep a reference to stdin and stdout to restore them later # when running under pytest we want to disable capture
stdin_backup = os.dup(sys.stdin.fileno()) with mock.patch.object(sys, 'stdin', sys.__stdin__), \
stdout_backup = os.dup(sys.stdout.fileno()) mock.patch.object(sys, 'stdout', sys.__stdout__):
# replace stdin with a pipe that will write 123 # keep a reference to stdin and stdout to restore them later
child_stdin_r, child_stdin_w = os.pipe() stdin_backup = os.dup(sys.stdin.fileno())
os.write(child_stdin_w, b"123") stdout_backup = os.dup(sys.stdout.fileno())
os.close(child_stdin_w)
os.dup2(child_stdin_r, sys.stdin.fileno()) # replace stdin with a pipe that will write 123
child_stdin_r, child_stdin_w = os.pipe()
# and stdout with the pipe to capture output os.write(child_stdin_w, b"123")
child_stdout_r, child_stdout_w = os.pipe() os.close(child_stdin_w)
os.dup2(child_stdout_w, sys.stdout.fileno()) os.dup2(child_stdin_r, sys.stdin.fileno())
try: # and stdout with the pipe to capture output
program = slapos.grid.utils.SlapPopen( child_stdout_r, child_stdout_w = os.pipe()
self.script.name, os.dup2(child_stdout_w, sys.stdout.fileno())
debug=True,
logger=logging.getLogger()) try:
# program output program = slapos.grid.utils.SlapPopen(
self.assertEqual(b'exit code?\n', os.read(child_stdout_r, 1024)) self.script.name,
debug=True,
self.assertEqual(123, program.returncode) logger=logging.getLogger())
self.assertEqual('(output not captured in debug mode)', program.output) # program output
finally: self.assertEqual(b'exit code?\n', os.read(child_stdout_r, 1024))
# restore stdin & stderr
os.dup2(stdin_backup, sys.stdin.fileno()) self.assertEqual(123, program.returncode)
os.dup2(stdout_backup, sys.stdout.fileno()) self.assertEqual('(output not captured in debug mode)', program.output)
# close all fds open for the test finally:
for fd in (child_stdin_r, child_stdout_r, child_stdout_w, stdin_backup, stdout_backup): # restore stdin & stderr
os.close(fd) os.dup2(stdin_backup, sys.stdin.fileno())
os.dup2(stdout_backup, sys.stdout.fileno())
# close all fds open for the test
for fd in (child_stdin_r, child_stdout_r, child_stdout_w, stdin_backup, stdout_backup):
os.close(fd)
...@@ -36,7 +36,7 @@ from slapos.grid.SlapObject import Partition, Software ...@@ -36,7 +36,7 @@ from slapos.grid.SlapObject import Partition, Software
from slapos.grid import utils from slapos.grid import utils
from slapos.grid import networkcache from slapos.grid import networkcache
# XXX: BasicMixin should be in a separated module, not in slapgrid test module. # XXX: BasicMixin should be in a separated module, not in slapgrid test module.
from slapos.tests.slapgrid import BasicMixin from slapos.tests.test_slapgrid import BasicMixin
# Mockup # Mockup
# XXX: Ambiguous name # XXX: Ambiguous name
......
...@@ -49,7 +49,7 @@ import pwd ...@@ -49,7 +49,7 @@ import pwd
import time import time
import mock import mock
from .slapgrid import DummyManager from .test_slapgrid import DummyManager
import six import six
......
...@@ -1136,7 +1136,7 @@ database_uri = %(tempdir)s/lib/external_proxy.db ...@@ -1136,7 +1136,7 @@ database_uri = %(tempdir)s/lib/external_proxy.db
behaviours. behaviours.
""" """
configuration = bytes2str(pkg_resources.resource_string( configuration = bytes2str(pkg_resources.resource_string(
'slapos.tests.slapproxy', 'slapos_multimaster.cfg.in' 'slapos.tests.test_slapproxy', 'slapos_multimaster.cfg.in'
)) % { )) % {
'tempdir': self._tempdir, 'proxyaddr': self.proxyaddr, 'tempdir': self._tempdir, 'proxyaddr': self.proxyaddr,
'external_proxy_host': self.external_proxy_host, 'external_proxy_host': self.external_proxy_host,
...@@ -1354,7 +1354,7 @@ class TestMigrateVersion10To12(TestInformation, TestRequest, TestSlaveRequest, T ...@@ -1354,7 +1354,7 @@ class TestMigrateVersion10To12(TestInformation, TestRequest, TestSlaveRequest, T
def setUp(self): def setUp(self):
super(TestMigrateVersion10To12, self).setUp() super(TestMigrateVersion10To12, self).setUp()
schema = bytes2str(pkg_resources.resource_string( schema = bytes2str(pkg_resources.resource_string(
'slapos.tests.slapproxy', 'slapos.tests.test_slapproxy',
'database_dump_version_10.sql' 'database_dump_version_10.sql'
)) % dict(version='12') )) % dict(version='12')
self.db = sqlite_connect(self.proxy_db) self.db = sqlite_connect(self.proxy_db)
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment