Python testtools.TestCase() Examples

The following are 30 code examples of testtools.TestCase(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module testtools , or try the search function .
Example #1
Source File: test_flaky.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_sends_start_on_start(self, jira_keys):
        """
        Flaky tests send ``startTest`` as soon as they start.

        This means that we see the name of the test in the trial reporter
        (FLOC-3511) and that the recorded duration of the test is more-or-less
        accurate (FLOC-3499)
        """
        log = []

        class FlakyTest(testtools.TestCase):
            run_tests_with = retry_flaky()

            @flaky(jira_keys, 1, 1)
            def test_delayed(self):
                # Get a copy of the event log at this point of the test.
                self.log = list(log)

        test = FlakyTest('test_delayed')
        result = ExtendedTestResult(log)
        test.run(result)
        self.assertThat(test.log, Equals([('startTest', test)])) 
Example #2
Source File: base.py    From python-tripleoclient with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.temp_homedir = self.useFixture(fixtures.TempHomeDir()).path

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #3
Source File: base.py    From bashate with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #4
Source File: test_runner.py    From green with MIT License 6 votes vote down vote up
def test_failedSaysSo(self):
        """
        A failing test case causes the whole run to report 'FAILED'
        """
        sub_tmpdir = tempfile.mkdtemp(dir=self.tmpdir)
        fh = open(os.path.join(sub_tmpdir, "test_failed.py"), "w")
        fh.write(
            dedent(
                """
            import unittest
            class Failed(unittest.TestCase):
                def test01(self):
                    self.assertTrue(False)
            """.format(
                    os.getpid()
                )
            )
        )
        fh.close()
        os.chdir(sub_tmpdir)
        tests = self.loader.loadTargets("test_failed")
        result = run(tests, self.stream, self.args)
        os.chdir(self.startdir)
        self.assertEqual(result.testsRun, 1)
        self.assertIn("FAILED", self.stream.getvalue()) 
Example #5
Source File: base.py    From tosca-parser with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #6
Source File: base.py    From DLRN with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        "Run before each test method to initialize test environment."

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #7
Source File: base.py    From heat-translator with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #8
Source File: base.py    From oslo.db with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #9
Source File: test_flaky.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_flaky_testtools_skipped_test(self, jira_keys, max_runs,
                                          min_passes, reasons):
        """
        If a test is skipped and also marked @flaky, we report it as skipped.
        """
        [min_passes, max_runs] = sorted([min_passes, max_runs])
        observed_reasons = []

        class SkippingTest(testtools.TestCase):
            run_tests_with = retry_flaky()

            @flaky(jira_keys, max_runs, min_passes)
            def test_skip(self):
                observed_reasons.append(reasons.next())
                self.skip(observed_reasons[-1])

        test = SkippingTest('test_skip')
        self.assertThat(run_test(test), only_skips(1, observed_reasons)) 
Example #10
Source File: test_flaky.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_intermittent_flaky_subclass(self, test_methods):
        """
        We sometimes subclass test classes in order to test different
        implementations of the same interface. A test within such a subclass
        can be marked as flaky, causing it to retry.
        """
        executions = iter(test_methods)

        class SomeTest(testtools.TestCase):
            run_tests_with = retry_flaky()

            def test_something(self):
                next(executions)()

        class SubclassTest(SomeTest):

            @flaky(u'FLOC-XXXX', max_runs=len(test_methods), min_passes=1)
            def test_something(self):
                super(SubclassTest, self).test_something()

        test = SubclassTest('test_something')
        self.assertThat(run_test(test), has_results(tests_run=Equals(1))) 
Example #11
Source File: test_flaky.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_intermittent_flaky_test_that_errors(self, test_methods):
        """
        Tests marked with 'flaky' are retried if they fail, and marked as
        erroring / failing if they don't reach the minimum number of successes.
        """
        executions = iter(test_methods)

        class SomeTest(testtools.TestCase):
            run_tests_with = retry_flaky()

            @flaky(u'FLOC-XXXX', max_runs=len(test_methods), min_passes=2)
            def test_something(self):
                next(executions)()

        test = SomeTest('test_something')
        self.assertThat(run_test(test), has_results(
            tests_run=Equals(1),
            errors=HasLength(1),
        )) 
Example #12
Source File: base.py    From oslo.vmware with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #13
Source File: test_flaky.py    From flocker with Apache License 2.0 6 votes vote down vote up
def test_successful_flaky_test(self):
        """
        A successful flaky test is considered successful.
        """

        # We use 'testtools' here to avoid accidentally depending on Twisted
        # TestCase features, thus increasing complexity.
        class SomeTest(testtools.TestCase):

            run_tests_with = retry_flaky()

            @flaky(u'FLOC-XXXX')
            def test_something(self):
                pass

        test = SomeTest('test_something')
        self.assertThat(run_test(test), has_results(tests_run=Equals(1))) 
Example #14
Source File: base.py    From python-magnumclient with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 60)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid, set a default timeout.
            test_timeout = 60
        if test_timeout <= 0:
            test_timeout = 60
        self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #15
Source File: base.py    From oslo.utils with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        """Run before each test method to initialize test environment."""

        super(TestCase, self).setUp()
        test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
        try:
            test_timeout = int(test_timeout)
        except ValueError:
            # If timeout value is invalid do not set a timeout.
            test_timeout = 0
        if test_timeout > 0:
            self.useFixture(fixtures.Timeout(test_timeout, gentle=True))

        self.useFixture(fixtures.NestedTempfile())
        self.useFixture(fixtures.TempHomeDir())

        if os.environ.get('OS_STDOUT_CAPTURE') in _TRUE_VALUES:
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if os.environ.get('OS_STDERR_CAPTURE') in _TRUE_VALUES:
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))

        self.log_fixture = self.useFixture(fixtures.FakeLogger()) 
Example #16
Source File: base.py    From stestr with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestCase, self).setUp()
        stdout = self.useFixture(fixtures.StringStream('stdout')).stream
        self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        stderr = self.useFixture(fixtures.StringStream('stderr')).stream
        self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr))
        self.useFixture(fixtures.LoggerFixture(nuke_handlers=False,
                                               level=None)) 
Example #17
Source File: test_logical_partition.py    From pypowervm with Apache License 2.0 5 votes vote down vote up
def test_desig_ipl_src(self):
        self.assertEqual('b', self.dwrap.desig_ipl_src)
        self.dwrap.desig_ipl_src = 'c'
        self.assertEqual('c', self.dwrap.desig_ipl_src)
        # Argh, testtools.TestCase overrides assertRaises - can't use 'with'
        try:
            self.dwrap.desig_ipl_src = 'q'
            self.fail()
        except ValueError:
            pass 
Example #18
Source File: test_compat.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def setUp(self):
        testtools.TestCase.setUp(self)
        dir = tempfile.mkdtemp()
        self.addCleanup(os.rmdir, dir)
        self.filename = os.path.join(dir, self.id().rsplit(".", 1)[1] + ".py")
        self._written = False 
Example #19
Source File: test_content.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_simple(self):
        class SomeTest(TestCase):
            def test_foo(self):
                pass
        test = SomeTest('test_foo')
        data = 'some data'
        path = self.make_file(data)
        my_content = text_content(data)
        attach_file(test, path, name='foo')
        self.assertEqual({'foo': my_content}, test.getDetails()) 
Example #20
Source File: test_content.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_optional_name(self):
        # If no name is provided, attach_file just uses the base name of the
        # file.
        class SomeTest(TestCase):
            def test_foo(self):
                pass
        test = SomeTest('test_foo')
        path = self.make_file('some data')
        base_path = os.path.basename(path)
        attach_file(test, path)
        self.assertEqual([base_path], list(test.getDetails())) 
Example #21
Source File: test_content.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_lazy_read(self):
        class SomeTest(TestCase):
            def test_foo(self):
                pass
        test = SomeTest('test_foo')
        path = self.make_file('some data')
        attach_file(test, path, name='foo', buffer_now=False)
        content = test.getDetails()['foo']
        content_file = open(path, 'w')
        content_file.write('new data')
        content_file.close()
        self.assertEqual(''.join(content.iter_text()), 'new data') 
Example #22
Source File: test_content.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_eager_read_by_default(self):
        class SomeTest(TestCase):
            def test_foo(self):
                pass
        test = SomeTest('test_foo')
        path = self.make_file('some data')
        attach_file(test, path, name='foo')
        content = test.getDetails()['foo']
        content_file = open(path, 'w')
        content_file.write('new data')
        content_file.close()
        self.assertEqual(''.join(content.iter_text()), 'some data') 
Example #23
Source File: utils.py    From python-magnumclient with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestCase, self).setUp()
        if (os.environ.get('OS_STDOUT_CAPTURE') == 'True' or
                os.environ.get('OS_STDOUT_CAPTURE') == '1'):
            stdout = self.useFixture(fixtures.StringStream('stdout')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        if (os.environ.get('OS_STDERR_CAPTURE') == 'True' or
                os.environ.get('OS_STDERR_CAPTURE') == '1'):
            stderr = self.useFixture(fixtures.StringStream('stderr')).stream
            self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) 
Example #24
Source File: test_run.py    From pth-toolkit with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self):
            self.package = fixtures.PythonPackage(
            'runexample', [('__init__.py', _b("""
from testtools import TestCase

class TestFoo(TestCase):
    def test_bar(self):
        pass
    def test_quux(self):
        pass
def test_suite():
    from unittest import TestLoader
    return TestLoader().loadTestsFromName(__name__)
"""))]) 
Example #25
Source File: osc_utils.py    From python-magnumclient with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        testtools.TestCase.setUp(self)

        if (os.environ.get("OS_STDOUT_CAPTURE") == "True" or
                os.environ.get("OS_STDOUT_CAPTURE") == "1"):
            stdout = self.useFixture(fixtures.StringStream("stdout")).stream
            self.useFixture(fixtures.MonkeyPatch("sys.stdout", stdout))

        if (os.environ.get("OS_STDERR_CAPTURE") == "True" or
                os.environ.get("OS_STDERR_CAPTURE") == "1"):
            stderr = self.useFixture(fixtures.StringStream("stderr")).stream
            self.useFixture(fixtures.MonkeyPatch("sys.stderr", stderr)) 
Example #26
Source File: base.py    From git-stacktrace with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestCase, self).setUp()
        stdout = self.useFixture(fixtures.StringStream('stdout')).stream
        self.useFixture(fixtures.MonkeyPatch('sys.stdout', stdout))
        stderr = self.useFixture(fixtures.StringStream('stderr')).stream
        self.useFixture(fixtures.MonkeyPatch('sys.stderr', stderr)) 
Example #27
Source File: base.py    From bifrost with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        super(TestCase, self).setUp() 
Example #28
Source File: test_runtest.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_catches_generator_tests(self):
        class BrokenTests(TestCase):

            run_tests_with = self.executor

            def test(self):
                yield None

        test = BrokenTests("test")
        result = test.run()

        self.assertThat(result.errors, HasLength(1))
        self.assertThat(
            result.errors[0],
            MatchesListwise(
                (
                    Is(test),
                    DocTestMatches(
                        """\
                ...InvalidTest:
                    Test returned a generator. Should it be
                    decorated with inlineCallbacks?
                """
                    ),
                )
            ),
        ) 
Example #29
Source File: base.py    From shade with Apache License 2.0 5 votes vote down vote up
def assertEqual(self, first, second, *args, **kwargs):
        '''Munch aware wrapper'''
        if isinstance(first, munch.Munch):
            first = first.toDict()
        if isinstance(second, munch.Munch):
            second = second.toDict()
        return super(TestCase, self).assertEqual(
            first, second, *args, **kwargs) 
Example #30
Source File: base.py    From senlin with Apache License 2.0 5 votes vote down vote up
def patchobject(self, obj, attr, **kwargs):
        mockfixture = self.useFixture(fixtures.MockPatchObject(obj, attr,
                                                               **kwargs))
        return mockfixture.mock

    # NOTE(pshchelo): this overrides the testtools.TestCase.patch method
    # that does simple monkey-patching in favor of mock's patching