[Piglit] [PATCH 25/49] unittests: port log tests to pylint

Dylan Baker dylan at pnwbakers.com
Fri Jul 29 18:39:11 UTC 2016


Signed-off-by: Dylan Baker <dylanx.c.baker at intel.com>
---
 unittests/framework/test_log.py | 193 ++++++++++++++++++++++++++++++++++++++++
 unittests/log_tests.py          | 171 -----------------------------------
 2 files changed, 193 insertions(+), 171 deletions(-)
 create mode 100644 unittests/framework/test_log.py
 delete mode 100644 unittests/log_tests.py

diff --git a/unittests/framework/test_log.py b/unittests/framework/test_log.py
new file mode 100644
index 0000000..1e6b714
--- /dev/null
+++ b/unittests/framework/test_log.py
@@ -0,0 +1,193 @@
+# Copyright (c) 2014, 2016 Intel Corporation
+
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+
+# The above copyright notice and this permission notice shall be included in
+# all copies or substantial portions of the Software.
+
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+"""Tests for log.py module."""
+
+from __future__ import (
+    absolute_import, division, print_function, unicode_literals
+)
+import collections
+import sys
+import threading
+
+import pytest
+import six
+
+import framework.log as log
+
+# pylint: disable=no-self-use,protected-access
+
+
+ at pytest.fixture
+def log_state():
+    """Create a unique state instance per test."""
+    return {'total': 1, 'complete': 0, 'lastlength': 0, 'running': [],
+            'summary': collections.defaultdict(lambda: 0)}
+
+
+class TestLogFactory(object):
+    """Tests for the LogFactory class."""
+
+    class TestGet(object):
+        """Tests for the LogFactory.get method."""
+
+        def test_returns_log(self):
+            """Returns a BaseLog derived instance."""
+            logger = log.LogManager('quiet', 100)
+            log_inst = logger.get()
+            assert isinstance(log_inst, log.BaseLog)
+
+    def test_log_state_update(self):
+        """log.BaseLog.log updates shared state managed by LogManager"""
+        logger = log.LogManager('quiet', 100)
+        log_inst = logger.get()
+        log_inst.log('pass')
+
+        assert logger._state['total'] == 100
+        assert logger._state['summary'] == {'pass': 1}
+        assert logger._state['complete'] == 1
+
+
+class TestQuietLog(object):
+    """Test QuietLog class."""
+
+    class TestOutput(object):
+        """Test the output of the various methods."""
+
+        @pytest.fixture(autouse=True, scope='function')
+        def mock_stdout(self, mocker):
+            mocker.patch.object(sys, 'stdout', six.StringIO())
+
+        def test_log(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test the output of the log method."""
+            quiet = log.QuietLog(log_state, threading.Lock())
+            quiet.log('pass')
+            sys.stdout.seek(0)
+
+            actual = sys.stdout.read()
+            assert actual == b'[1/1] pass: 1 -\n'
+
+        def test_summary(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test the output of the summary method."""
+            quiet = log.QuietLog(log_state, threading.Lock())
+            # Call log to set the total correctly, then truncate and remove the
+            # values, so the we can test
+            quiet.log('pass')
+            sys.stdout.seek(0)
+            sys.stdout.truncate()
+
+            quiet.summary()
+            sys.stdout.seek(0)
+
+            # Because of the 'lastlength' mechanims there will likely be
+            # trainling whitespace after the the output, it's not useful to
+            # test that here, so just strip it.
+            assert sys.stdout.read().rstrip() == b'[1/1] pass: 1'
+
+        def test_start(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test that the start method doesn't have output."""
+            quiet = log.QuietLog(log_state, threading.Lock())
+            quiet.start('foo')
+            sys.stdout.seek(0)
+
+            actual = sys.stdout.read()
+            assert actual == b''
+
+
+class TestVerboseLog(object):
+    """Tests for the VerboseLog class."""
+
+    class TestOutput(object):
+        """Test the output of the various methods."""
+
+        @pytest.fixture(autouse=True, scope='function')
+        def mock_stdout(self, mocker):
+            mocker.patch.object(sys, 'stdout', six.StringIO())
+
+        def test_log(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test the output of the log method."""
+            l = log.VerboseLog(log_state, threading.Lock())
+            l.start('foo')
+            sys.stdout.seek(0)
+            sys.stdout.truncate()
+
+            l.log('pass')
+            sys.stdout.seek(0)
+
+            actual = sys.stdout.read()
+            assert actual == b'pass: foo\n\n[1/1] pass: 1 /\n'
+
+        def test_summary(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test the output of the summary method."""
+            l = log.VerboseLog(log_state, threading.Lock())
+            l.log('pass')
+            sys.stdout.seek(0)
+            sys.stdout.truncate()
+
+            l.summary()
+            sys.stdout.seek(0)
+
+            assert sys.stdout.read().rstrip() == b'[1/1] pass: 1'
+
+        def test_start(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test that the start method doesn't have output."""
+            l = log.VerboseLog(log_state, threading.Lock())
+            l.start('foo')
+            sys.stdout.seek(0)
+
+            assert sys.stdout.read().rstrip() == b'running: foo\n\n[0/1]  \\'
+
+
+class TestDummyLog(object):
+    """Tests for the DummyLog class."""
+
+    class TestOutput(object):
+        """Test the output of the various methods."""
+
+        @pytest.fixture(autouse=True, scope='function')
+        def mock_stdout(self, mocker):
+            mocker.patch.object(sys, 'stdout', six.StringIO())
+
+        def test_log(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test the output of the log method."""
+            quiet = log.DummyLog(log_state, threading.Lock())
+            quiet.log('pass')
+            sys.stdout.seek(0)
+
+            actual = sys.stdout.read()
+            assert actual == b''
+
+        def test_summary(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test the output of the summary method."""
+            quiet = log.DummyLog(log_state, threading.Lock())
+            quiet.summary()
+            sys.stdout.seek(0)
+
+            actual = sys.stdout.read()
+            assert actual == b''
+
+        def test_start(self, log_state):  # pylint: disable=redefined-outer-name
+            """Test that the start method doesn't have output."""
+            quiet = log.DummyLog(log_state, threading.Lock())
+            quiet.start('foo')
+            sys.stdout.seek(0)
+
+            actual = sys.stdout.read()
+            assert actual == b''
diff --git a/unittests/log_tests.py b/unittests/log_tests.py
deleted file mode 100644
index 40a9c15..0000000
--- a/unittests/log_tests.py
+++ /dev/null
@@ -1,171 +0,0 @@
-# Copyright (c) 2014 Intel Corporation
-
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-# SOFTWARE.
-
-""" Module provides tests for log.py module """
-
-from __future__ import (
-    absolute_import, division, print_function, unicode_literals
-)
-import sys
-import collections
-import threading
-
-import nose.tools as nt
-
-import framework.log as log
-from . import utils
-
-TEST_STATE = {'total': 0, 'complete': 0, 'lastlength': 0, 'running': [],
-              'summary': collections.defaultdict(lambda: 0)}
-
-
- at utils.nose.generator
-def test_initialize():
-    """ Generate tests for class initialization """
-    check_initialize = lambda c, *a: c(*a)
-
-    for name, class_ in [('QuiteLog', log.QuietLog),
-                         ('VerboseLog', log.VerboseLog)]:
-        check_initialize.description = "log.{}: class initializes".format(name)
-        yield check_initialize, class_, TEST_STATE, 'lock'  # TODO: use mock
-
-    check_initialize.description = "log.LogManager: class initializes"
-    yield check_initialize, log.LogManager, 'quiet', 100
-
-
-def test_log_factory_returns_log():
-    """log.LogManager.get() returns a BaseLog derived instance"""
-    logger = log.LogManager('quiet', 100)
-    log_inst = logger.get()
-    nt.ok_(isinstance(log_inst, log.BaseLog))
-
-
- at utils.nose.generator
-def test_quietlog_log_state_update():
-    """log.QuiteLog.log() updates shared state managed by LogManager"""
-    logger = log.LogManager('quiet', 100)
-    log_inst = logger.get()
-    log_inst.log('pass')
-
-    # This lambda is necissary, without it description cannot be set
-    check = lambda x, y: nt.assert_equal(x, y)
-    for name, value in [('total', 100), ('summary', {'pass': 1}),
-                        ('complete', 1)]:
-        check.description = \
-            'log.QuiteLog(): increments state value {0}'.format(name)
-        yield check, logger._state[name], value
-
-
-def check_for_output(func, args, file_=sys.stdout):
-    """ Test that a test produced output to either stdout or stderr
-
-    Arguments:
-    func -- a callable that will produce output
-    args -- any arguments to be passed to func as a container with a splat
-
-    KeywordArguments:
-    file -- should be either sys.stdout or sys.stderr. default: sys.stdout
-
-    """
-    # Ensure that the file is empty before running the test
-    file_.seek(0)
-    file_.truncate()
-
-    func(*args)
-    # In nose sys.stdout and sys.stderr is a StringIO object, it returns a
-    # string of everything after the tell.
-    nt.eq_(file_.read(), '')
-
-
- at utils.nose.generator
-def test_print_when_expected():
-    """ Generator that creates tests that ensure that methods print
-
-    For most logger classes <class>.log() and <class>.summary() should print
-    something, for some classes <class>.start() should print.
-
-    This doesn't try to check what they are printing, just that they are
-    printing, since 1) the output is very implementation dependent, and 2) it
-    is subject to change.
-
-    """
-    # a list of tuples which element 1 is the name of the class and method
-    # element 2 is a callable, and element 3 is a list of arguments to be
-    # passed to that callable. it needs to work with the splat operator
-    printing = []
-
-    # Test QuietLog
-    quiet = log.QuietLog(TEST_STATE, threading.Lock())  # TODO: use mock
-    printing.append(('QuietLog.log', quiet.log, ['pass']))
-    printing.append(('QuietLog.summary', quiet.summary, []))
-
-    # Test VerboseLog
-    verbose = log.VerboseLog(TEST_STATE, threading.Lock())  # TODO: use mock
-    printing.append(('VerboseLog.start', verbose.start, ['a test']))
-    printing.append(('VerboseLog.log', verbose.log, ['pass']))
-    printing.append(('VerboseLog.summary', verbose.summary, []))
-
-    for name, func, args in printing:
-        check_for_output.description = "log.{}: produces output".format(name)
-        yield check_for_output, func, args
-
-
-def check_no_output(func, args, file_=sys.stdout):
-    """ file should not be written into
-
-    This is the coralary of check_for_ouput, it takes the same arguments and
-    behaves the same way. See its docstring for more info
-
-    """
-    # Ensure that the file is empty before running the test
-    file_.seek(0)
-    file_.truncate()
-
-    func(*args)
-    file_.seek(0, 2)
-    nt.eq_(file_.tell(), 0,
-           msg='file.tell() is at {}, but should be at 0'.format(file_.tell()))
-
-
- at utils.nose.generator
-def test_noprint_when_expected():
-    """ Generate tests for methods that shouldn't print
-
-    some methods shouldn't print anything, ensure that they don't
-
-    """
-    # a list of tuples which element 1 is the name of the class and method
-    # element 2 is a callable, and element 3 is a list of arguments to be
-    # passed to that callable. it needs to work with the splat operator
-    printing = []
-
-    # Test QuietLog
-    quiet = log.QuietLog(TEST_STATE, threading.Lock())  # TODO: use mock
-    printing.append(('QuietLog.start', quiet.start, ['name']))
-
-    # Test DummyLog
-    dummy = log.DummyLog(TEST_STATE, threading.Lock())  # TODO: use mock
-    printing.append(('DummyLog.start', dummy.start, ['name']))
-    printing.append(('DummyLog.log', dummy.log, ['pass']))
-    printing.append(('DummyLog.summary', dummy.summary, []))
-
-    for name, func, args in printing:
-        check_no_output.description = "log.{}: produces no output".format(name)
-        yield check_no_output, func, args
-- 
2.9.0



More information about the Piglit mailing list