[Piglit] [PATCH 35/42] tests/utils.py: reorganize the utils to be more readable

Dylan Baker baker.dylan.c at gmail.com
Wed Apr 22 15:10:24 PDT 2015


This just moves code around.

Signed-off-by: Dylan Baker <dylanx.c.baker at intel.com>
---
 framework/tests/utils.py | 209 +++++++++++++++++++++++------------------------
 1 file changed, 102 insertions(+), 107 deletions(-)

diff --git a/framework/tests/utils.py b/framework/tests/utils.py
index 10b48f6..967204e 100644
--- a/framework/tests/utils.py
+++ b/framework/tests/utils.py
@@ -25,9 +25,6 @@ in a single place.
 
 """
 
-# TODO: add a chdir decorator that gets the current dir, runs the test in a
-#       try and returns to the start dir in the finally
-
 from __future__ import print_function, absolute_import
 import os
 import sys
@@ -42,7 +39,6 @@ try:
 except ImportError:
     import json
 from nose.plugins.skip import SkipTest
-import nose.tools as nt
 
 from framework import test, backends, results
 
@@ -93,49 +89,81 @@ class UtilsError(Exception):
     pass
 
 
- at contextmanager
-def resultfile():
-    """ Create a stringio with some json in it and pass that as results """
-    with tempfile.NamedTemporaryFile(delete=False) as output:
-        json.dump(JSON_DATA, output)
+class StaticDirectory(object):
+    """ Helper class providing shared files creation and cleanup
 
-    yield output
+    One should override the setup_class method in a child class, call super(),
+    and then add files to cls.dir.
 
-    os.remove(output.name)
+    Tests in this class should NOT modify the contents of tidr, if you want
+    that functionality you want a different class
 
+    """
+    @classmethod
+    def setup_class(cls):
+        """ Create a temperary directory that will be removed in teardown_class
+        """
+        cls.tdir = tempfile.mkdtemp()
 
- at contextmanager
-def with_tempfile(contents):
-    """ Provides a context manager for a named tempfile
+    @classmethod
+    def teardown_class(cls):
+        """ Remove the temporary directory """
+        shutil.rmtree(cls.tdir)
 
-    This contextmanager creates a named tempfile, writes data into that
-    tempfile, then closes it and yields the filepath. After the context is
-    returned it closes and removes the tempfile.
+
+class DocFormatter(object):
+    """Decorator for formatting object docstrings.
+
+    This class is designed to be initialized once per test module, and then one
+    instance used as a decorator for all functions.
+
+    Works as follows:
+    >>> doc_formatter = DocFormatter({'format': 'foo', 'name': 'bar'})
+    >>>
+    >>> @doc_formatter
+    ... def foo():
+    ...     '''a docstring for {format} and {name}'''
+    ...     pass
+    ...
+    >>> foo.__doc__
+    'a docstring for foo and bar'
+
+    This allows tests that can be dynamically updated by changing a single
+    constant to have the test descriptions alos updated by the same constant.
 
     Arguments:
-    contests -- This should be a string (unicode or str), in which case it is
-                written directly into the file.
+    table -- a dictionary of key value pairs to be converted
 
     """
-    # Do not delete the tempfile as soon as it is closed
-    temp = tempfile.NamedTemporaryFile(delete=False)
-    temp.write(contents)
-    temp.close()
+    def __init__(self, table):
+        self.__table = table
 
-    yield temp.name
+    def __call__(self, func):
+        try:
+            func.__doc__ = func.__doc__.format(**self.__table)
+        except KeyError as e:
+            # We want to catch this to ensure that a test that is looking for a
+            # KeyError doesn't pass when it shouldn't
+            raise UtilsError(e)
 
-    os.remove(temp.name)
+        return func
 
 
- at contextmanager
-def tempdir():
-    """ Creates a temporary directory, returns it, and then deletes it """
-    tdir = tempfile.mkdtemp()
-    yield tdir
-    shutil.rmtree(tdir)
+class Test(test.Test):
+    """A basic dmmmy Test class that can be used in places a test is required.
+
+    This provides dummy version of abstract methods in
+    framework.test.base.Test, which allows it to be initialized and run, but is
+    unlikely to be useful for running.
+
+    This is mainly intended for testing where a Test class is required, but
+    doesn't need to be run.
+
+    """
+    def interpret_result(self):
+        pass
 
 
- at nt.nottest
 class GeneratedTestWrapper(object):
     """ An object proxy for nose test instances
 
@@ -175,6 +203,48 @@ class GeneratedTestWrapper(object):
         return self._wrapped(*args, **kwargs)
 
 
+ at contextmanager
+def resultfile():
+    """ Create a stringio with some json in it and pass that as results """
+    with tempfile.NamedTemporaryFile(delete=False) as output:
+        json.dump(JSON_DATA, output)
+
+    yield output
+
+    os.remove(output.name)
+
+
+ at contextmanager
+def with_tempfile(contents):
+    """ Provides a context manager for a named tempfile
+
+    This contextmanager creates a named tempfile, writes data into that
+    tempfile, then closes it and yields the filepath. After the context is
+    returned it closes and removes the tempfile.
+
+    Arguments:
+    contests -- This should be a string (unicode or str), in which case it is
+                written directly into the file.
+
+    """
+    # Do not delete the tempfile as soon as it is closed
+    temp = tempfile.NamedTemporaryFile(delete=False)
+    temp.write(contents)
+    temp.close()
+
+    yield temp.name
+
+    os.remove(temp.name)
+
+
+ at contextmanager
+def tempdir():
+    """ Creates a temporary directory, returns it, and then deletes it """
+    tdir = tempfile.mkdtemp()
+    yield tdir
+    shutil.rmtree(tdir)
+
+
 def nose_generator(func):
     """ Decorator for nose test generators to us GeneratedTestWrapper
 
@@ -202,28 +272,6 @@ def privileged_test(func):
     return func
 
 
-class StaticDirectory(object):
-    """ Helper class providing shared files creation and cleanup
-
-    One should override the setup_class method in a child class, call super(),
-    and then add files to cls.dir.
-
-    Tests in this class should NOT modify the contents of tidr, if you want
-    that functionality you want a different class
-
-    """
-    @classmethod
-    def setup_class(cls):
-        """ Create a temperary directory that will be removed in teardown_class
-        """
-        cls.tdir = tempfile.mkdtemp()
-
-    @classmethod
-    def teardown_class(cls):
-        """ Remove the temporary directory """
-        shutil.rmtree(cls.tdir)
-
-
 def binary_check(bin_):
     """Check for the existance of a binary or raise SkipTest."""
     with open(os.devnull, 'w') as null:
@@ -239,21 +287,6 @@ def platform_check(plat):
         raise SkipTest('Platform {} is not supported'.format(sys.platform))
 
 
-class Test(test.Test):
-    """A basic dmmmy Test class that can be used in places a test is required.
-
-    This provides dummy version of abstract methods in
-    framework.test.base.Test, which allows it to be initialized and run, but is
-    unlikely to be useful for running.
-
-    This is mainly intended for testing where a Test class is required, but
-    doesn't need to be run.
-
-    """
-    def interpret_result(self):
-        pass
-
-
 def fail_if(function, values, exceptions, except_error=False):
     """function fails if any of the exceptions are raised.
 
@@ -314,44 +347,6 @@ def no_error(func):
     return test_wrapper
 
 
-class DocFormatter(object):
-    """Decorator for formatting object docstrings.
-
-    This class is designed to be initialized once per test module, and then one
-    instance used as a decorator for all functions.
-
-    Works as follows:
-    >>> doc_formatter = DocFormatter({'format': 'foo', 'name': 'bar'})
-    >>>
-    >>> @doc_formatter
-    ... def foo():
-    ...     '''a docstring for {format} and {name}'''
-    ...     pass
-    ...
-    >>> foo.__doc__
-    'a docstring for foo and bar'
-
-    This allows tests that can be dynamically updated by changing a single
-    constant to have the test descriptions alos updated by the same constant.
-
-    Arguments:
-    table -- a dictionary of key value pairs to be converted
-
-    """
-    def __init__(self, table):
-        self.__table = table
-
-    def __call__(self, func):
-        try:
-            func.__doc__ = func.__doc__.format(**self.__table)
-        except KeyError as e:
-            # We want to catch this to ensure that a test that is looking for a
-            # KeyError doesn't pass when it shouldn't
-            raise UtilsError(e)
-
-        return func
-
-
 def test_in_tempdir(func):
     """Decorator that moves to a new directory to run a test.
 
-- 
2.3.5



More information about the Piglit mailing list