Esempio n. 1
0
    def testNoExit(self):
        result = object()
        test = object()

        class FakeRunner(object):
            def run(self, test):
                self.test = test
                return result

        runner = FakeRunner()

        oldParseArgs = unittest.TestProgram.parseArgs

        def restoreParseArgs():
            unittest.TestProgram.parseArgs = oldParseArgs

        unittest.TestProgram.parseArgs = lambda *args: None
        self.addCleanup(restoreParseArgs)

        def removeTest():
            del unittest.TestProgram.test

        unittest.TestProgram.test = test
        self.addCleanup(removeTest)

        program = unittest.TestProgram(testRunner=runner,
                                       exit=False,
                                       verbosity=2)

        self.assertEqual(program.result, result)
        self.assertEqual(runner.test, test)
        self.assertEqual(program.verbosity, 2)
Esempio n. 2
0
def main():
    script_dir = os.path.join(os.getcwd(), os.path.dirname(__file__))
    argv = [
        sys.argv[0], 'discover', '--top-level-dir', script_dir, '--pattern',
        '*.py'
    ] + sys.argv[1:]
    unittest.TestProgram(testLoader=TestLoader(), argv=argv)
Esempio n. 3
0
def main():
    omit = ["hftools/_external/*.py"]
    omit = None
    if "--coverage" in sys.argv:
        docoverage = True
        del sys.argv[sys.argv.index("--coverage")]
    else:
        docoverage = False

    if docoverage:
        try:
            import coverage
            cover_config = os.path.join(os.path.split(__file__)[0],
                                        configpath)
            cov = coverage.coverage(source=["hftools"],
                                    config_file=cover_config)
            cov.start()
        except ImportError:
            if docoverage:
                print("coverage module is missing. Running tests "
                      "without coverage")
            docoverage = False

    runner = unittest.TextTestRunner  # OBS do not instantiate class!
    prog = unittest.TestProgram(module=None, testRunner=runner, exit=False)

    if docoverage:
        cov.stop()
        import hftools
        covhtmldir = pjoin(psplit(psplit(hftools.__file__)[0])[0], "covhtml")
        cov.html_report(directory=covhtmldir)
def main():
    script_dir = os.path.join(os.getcwd(), os.path.dirname(__file__))
    # print('old argv: {}'.format(sys.argv))
    argv = [sys.argv[0],
            'discover',
            '--top-level-directory', script_dir,
            '--pattern', '*.py'] + sys.argv[1:]
    unittest.TestProgram(testLoader=TestLoader(), argv=argv, module=None)
Esempio n. 5
0
    def testVerbosity(self):
#        program = self.program
#
#        for opt in '-q', '--quiet':
#            program.verbosity = 1
#            program.parseArgs([None, opt])
#            self.assertEqual(program.verbosity, 0)
        program = unittest.TestProgram(tests=None, quiet=True)                  ###
        self.assertEqual(program.verbosity, 0)                                  ###
Esempio n. 6
0
def main(argv=None):
    if argv is None:
        argv = sys.argv

    # Set the argparse module to test.
    # TODO: make this toggleable with a command-line argument.
    argparse2.test.module_under_test = argparse2
    # The following is what `python -m unittest` does in Python 3.4.
    unittest.TestProgram(module=None)
def test_engine(engine):
    global JSEngine, ctx
    print('\nStart test %s' % engine.__name__)
    if engine is ExternalJSEngine:
        print('Used external interpreter: %r' % jsengine.external_interpreter)
    JSEngine = engine
    ctx = None
    unittest.TestProgram(exit=False)
    print('End test %s\n' % engine.__name__)
Esempio n. 8
0
 def setUpClass(cls):
     test_program = unittest.TestProgram(
         module="contextional.test_resources.success",
         testRunner=SilentTestRunner,
         argv=["contextional/tests/test_success.py"],
         exit=False,
         verbosity=2,
     )
     cls.test_results = test_program.result
     cls.stream_output = cls.test_results.test_run_output
Esempio n. 9
0
    def testParseArgsNonExistentFiles(self):
        program = unittest.TestProgram(tests=None)  ###
        argv = ['progname', 'foo/bar/baz.py', 'green\\red.py']
        program.tests = argv[1:]  ###
        self._patch_isfile([])

        program.createTests = lambda: None
        program.parseArgs(argv)

        self.assertEqual(program.testNames, argv[1:])
Esempio n. 10
0
    def testParseArgsFilePaths(self):
        program = unittest.TestProgram(tests=None)  ###
        argv = ['progname', 'foo/bar/baz.py', 'green\\red.py']
        program.tests = argv[1:]  ###
        self._patch_isfile(argv)

        program.createTests = lambda: None
        program.parseArgs(argv)

        expected = ['foo.bar.baz', 'green.red']
        self.assertEqual(program.testNames, expected)
Esempio n. 11
0
def main():
    script_dir = os.path.join(os.getcwd(), os.path.dirname(__file__))

    # The doctests expect to be run from the "switch_mod" directory in
    # order to find test_dat.
    os.chdir(os.path.join(script_dir, 'switch_mod'))

    argv = [sys.argv[0],
            'discover',
            '--top-level-dir', script_dir,
            '--pattern', '*.py'] + sys.argv[1:]
    unittest.TestProgram(testLoader=TestLoader(), argv=argv)
Esempio n. 12
0
    def test_defaultTest_with_string(self):
        class FakeRunner(object):
            def run(self, test):
                self.test = test
                return True

        runner = FakeRunner()
        program = unittest.TestProgram(testRunner=runner,
                                       exit=False,
                                       defaultTest='unittest.test',
                                       testLoader=self.FooBarLoader())
        self.assertEqual(('unittest.test', ), program.testNames)
Esempio n. 13
0
 def _run_normal_tests():
     """Run other/normal tests"""
     with CoverageContext(coverage_kwargs=dict(
             cover_pylib=False,
             branch=True,
             data_suffix=True,
             config_file='normal/.coveragerc')) as coverage:
         tests = unittest.TestProgram(
             module=None,
             exit=False,
             argv=['normal_tests', 'discover', '-s', 'normal'])
     coverage.coverage.save()
     return tests
Esempio n. 14
0
def main():
    global exit_code
    try:
        try:
            #p = unittest.TestProgram(runNow=False)
            p = unittest.TestProgram()
            # This should always be the last test case run.
            p.test.addTest(ThreadFailedTest('test_threads_failed'))
            p.runTests()
        except SystemExit, e:
            exit_code = e.code
    finally:
        coro.set_exit(exit_code)
Esempio n. 15
0
    def testParseArgsFileNames(self):
        # running tests with filenames instead of module names
        program = unittest.TestProgram(tests=None)  ###
        argv = ['progname', 'foo.py', 'bar.Py', 'baz.PY', 'wing.txt']
        program.tests = argv[1:]  ###
        self._patch_isfile(argv)

        program.createTests = lambda: None
        program.parseArgs(argv)

        # note that 'wing.txt' is not a Python file so the name should
        # *not* be converted to a module name
        expected = ['foo', 'bar', 'baz', 'wing.txt']
        self.assertEqual(program.testNames, expected)
Esempio n. 16
0
    def testParseArgsAbsolutePathsThatCanBeConverted(self):
        cur_dir = os.getcwd()
#        program = self.program
        program = unittest.TestProgram(tests=None)                              ###
        def _join(name):
            return os.path.join(cur_dir, name)
        argv = ['progname', _join('foo/bar/baz.py'), _join('green\\red.py')]
        program.tests = argv[1:]                                                ###
        self._patch_isfile(argv)

        program.createTests = lambda: None
        program.parseArgs(argv)

        expected = ['foo.bar.baz', 'green.red']
        self.assertEqual(program.testNames, expected)
Esempio n. 17
0
    def test_defaultTest_with_iterable(self):
        class FakeRunner(object):
            def run(self, test):
                self.test = test
                return True

        old_argv = sys.argv
        sys.argv = ['faketest']
        runner = FakeRunner()
        program = unittest.TestProgram(
            testRunner=runner, exit=False,
            defaultTest=['unittest.test', 'unittest.test2'],
            testLoader=self.FooBarLoader())
        sys.argv = old_argv
        self.assertEqual(['unittest.test', 'unittest.test2'],
                          program.testNames)
Esempio n. 18
0
def main():
    with unittest.mock.patch.object(unittest.TestProgram, 'runTests'):
        test_program = unittest.TestProgram()
        test_runner = unittest.runner.TextTestRunner
        try:
            # noinspection PyUnresolvedReferences
            test_runner = test_runner(
                verbosity=test_program.verbosity,
                failfast=test_program.failfast,
                buffer=test_program.buffer,
                warnings=test_program.warnings,
                tb_locals=test_program.tb_locals)
        except TypeError:
            # didn't accept the tb_locals argument
            test_runner = test_runner(
                verbosity=test_program.verbosity,
                failfast=test_program.failfast,
                buffer=test_program.buffer,
                warnings=test_program.warnings)
        # noinspection PyUnresolvedReferences,PyProtectedMember
        api = UnitTestApi(test_runner=test_runner, suite=test_program.test._tests[0])
        create_test_gui(api)
Esempio n. 19
0
def RunInSingleDir(argv, xmlout, dirname):
    """ Run unittest TestProgram w/ given argv, first prepending dirname 
    to sys.path """

    saved_path = None
    if dirname != sys.path[0]:
        saved_path = list(sys.path)
        sys.path.insert(0, dirname)

    result = wingtest_common.XmlTestResult(xmlout)
    runner = wingtest_common.XmlTestRunner(result)
    try:
        try:
            unittest.TestProgram(argv=argv, module=None, testRunner=runner)
        except SystemExit:
            raise
        except Exception:
            # Note that import error from test files end up here, so this is
            # not just for runner exceptions
            xmlout._write_exc_info(sys.exc_info())
    finally:
        if saved_path is not None:
            sys.path = saved_path
Esempio n. 20
0
    def test_skip_works_with_collector(self):
        verbosity = 2
        stream = StringIO()
        runner = TestRunner(stream=stream, verbosity=verbosity)
        pwd = os.getcwd()

        # we don't need to see our own warnings
        warnings.filterwarnings(action='ignore',
                                category=RuntimeWarning,
                                module='nose.plugins.manager')

        try:
            os.chdir(os.path.join(support, 'issue038'))
            unittest.TestProgram(
                None, None,
                argv=['test_collector', '-v', 'nose.collector'],
                testRunner=runner)
        except SystemExit:
            pass
        os.chdir(pwd)
        out = stream.getvalue()
        assert runner.result.wasSuccessful()
        assert 'SKIP' in out, "SKIP not found in %s" % out
Esempio n. 21
0
 def run(self):
     logger.info('-------------- auto test start --------------')
     logger.info('create test database...')
     self._create_testdb()
     logger.info('change to start server of config file...')
     self._config()
     logger.info('sync table struct...')
     self._sync_db_struct()
     logger.info('init server data...')
     self._init_data()
     logger.info('start server...')
     self._start_server()
     logger.info('excute test case...')
     program = unittest.TestProgram(defaultTest="load", exit=False)
     logger.info('get test result...')
     result = self._generate_result(program)
     if result:
         logger.info('send email...')
         send_email(result)
     logger.info('delete database...')
     self._delete_testdb()
     logger.info('-------------- auto test end --------------')
     return result
Esempio n. 22
0
#
# Copyright (c) 2015-2017 Esteban Tovagliari, The appleseedhq Organization
#
# 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.
#

import unittest

from testbasis import *
from testdict2dict import *
from testentitymap import *
from testentityvector import *

unittest.TestProgram(testRunner=unittest.TextTestRunner())
Esempio n. 23
0
    @gen_test
    def test_exception(self):
        yield self.client.testException('Safe')

        try:
            yield self.client.testException('Xception')
        except Xception as ex:
            self.assertEqual(ex.errorCode, 1001)
            self.assertEqual(ex.message, 'Xception')
        else:
            self.fail("should have gotten exception")
        try:
            yield self.client.testException('throw_undeclared')
        except TTransportException as ex:
            pass
        else:
            self.fail("should have gotten exception")


def suite():
    suite = unittest.TestSuite()
    loader = unittest.TestLoader()
    suite.addTest(loader.loadTestsFromTestCase(ThriftTestCase))
    return suite


if __name__ == '__main__':
    unittest.TestProgram(defaultTest='suite',
                         testRunner=unittest.TextTestRunner(verbosity=1))
Esempio n. 24
0
    def test_repack(self):
        self.tdb.text["foo"] = "abc"
        self.tdb.text["bar"] = "def"
        del self.tdb.text["foo"]
        self.tdb.repack()

    def test_len(self):
        self.assertEquals(0, len(list(self.tdb.text)))
        self.tdb.text["entry"] = "value"
        self.assertEquals(1, len(list(self.tdb.text)))

    def test_text_and_binary(self):
        text = u'\xfa\u0148\xef\xe7\xf8\xf0\xea'
        bytestr = text.encode('utf-8')
        self.tdb[b"entry"] = bytestr
        self.tdb.text[u"entry2"] = text
        self.assertEquals(self.tdb.text["entry"], text)
        self.assertEquals(self.tdb[b"entry2"], bytestr)
        assert self.tdb.text.raw == self.tdb


class VersionTests(TestCase):
    def test_present(self):
        self.assertTrue(isinstance(tdb.__version__, str))


if __name__ == '__main__':
    import unittest
    unittest.TestProgram()
Esempio n. 25
0
            try:
                if os.path.isdir(dstp) and not os.path.islink(dstp):
                    shutil.rmtree(dstp)
                else:
                    os.unlink(dstp)
            except OSError:
                logging.exception("rem servers synchronization")
            if os.path.islink(srcp):
                os.symlink(os.readlink(srcp), dstp)
            elif os.path.isfile(srcp):
                shutil.copy2(srcp, dstp)
            elif os.path.isdir(srcp):
                shutil.copytree(srcp, dstp)
            else:
                raise RuntimeError("syncdir unexpected situation")

    def setUp(self):
        path1 = getattr(getattr(self, "server1", None), "path", None)
        path2 = getattr(getattr(self, "server2", None), "path", None)
        if path1 and path2:
            testdir.common.RestartService(path1)
            with testdir.common.ServiceTemporaryShutdown(path2):
                self.__sync_dir(path1, path2, ["client", "rem", "rem-server.py", "start-stop-daemon.py", "setup_env.sh",
                                               "network_topology.cfg"])


if __name__ == "__main__":
    config = Configuration.GetLocalConfig()
    testdir.setUp(config, "userdata")
    unittest.TestProgram(module=testdir)
Esempio n. 26
0
from RelativePreset import TestRelativePreset
from LookupTest import LookupTest
from ParameterAlgoTest import ParameterAlgoTest
from CamelCaseTest import CamelCaseTest
from LRUCacheTest import LRUCacheTest
from DataInterleaveOpTest import DataInterleaveOpTest
from DataConvertOpTest import DataConvertOpTest
from ConfigLoaderTest import ConfigLoaderTest
from MurmurHashTest import MurmurHashTest
from BoolVectorData import BoolVectorDataTest
from CompoundParameterTest import CompoundParameterTest
from ImfTest import *
from TimeCodeDataTest import TimeCodeDataTest
from NullObjectTest import NullObjectTest
from StandardRadialLensModelTest import StandardRadialLensModelTest
from ObjectPoolTest import ObjectPoolTest
from RefCountedTest import RefCountedTest
from DataAlgoTest import DataAlgoTest
from PolygonAlgoTest import PolygonAlgoTest
from BoxAlgoTest import BoxAlgoTest
from RandomAlgoTest import RandomAlgoTest
from ReprTest import ReprTest
from StringAlgoTest import StringAlgoTest
from PathMatcherTest import PathMatcherTest
from PathMatcherDataTest import PathMatcherDataTest

unittest.TestProgram(
    testRunner=unittest.TextTestRunner(stream=IECore.CompoundStream(
        [sys.stderr, open("test/IECore/resultsPython.txt", "w")]),
                                       verbosity=2))
Esempio n. 27
0
if __name__ == "__main__":
    import unittest
    import doctest
    import database
    import models

    import test_serialize

    doctest.testmod()
    doctest.testmod(m=database)
    doctest.testmod(m=models)

    unittest.TestProgram(test_serialize)
Esempio n. 28
0
        request._place = self._moduleDict[self._typeModuleName].ns1.Place_Def()
        request._place._City = 'Seattle'
        request._place._State = 'Washington'
        request._place._Country = 'United States'
        try:
            response = self.RPC(operationName, request)
        except EvaluateException, ex:
            pass

    def test_GetPlaceList(self):
        operationName = 'GetPlaceList'
        request = self.getInputMessageInstance(operationName)
        request._placeName = 'New York'
        request._MaxItems = 5
        request._imagePresence = 0
        try:
            response = self.RPC(operationName, request)
        except EvaluateException, ex:
            pass


def makeTestSuite():
    suite = ServiceTestSuite()
    suite.addTest(unittest.makeSuite(TerraServiceTest, 'test_'))
    suite.addTest(unittest.makeSuite(TerraServiceTestFailures, 'test_'))
    return suite


if __name__ == "__main__":
    unittest.TestProgram(defaultTest="makeTestSuite")
Esempio n. 29
0
# mock out warning registry
import os, sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

import MAGSBS
import unittest, unittest.mock

# Running tests will load the built-in MAGSBS localisation support which is not
# available during test runtime. Hence it's better mocked out. For the few rare
# cases where the warning registry is under test, the mock can be added using a
# patch to the test function.
import MAGSBS.common

with unittest.mock.patch("MAGSBS.common.WarningRegistry"):
    MAGSBS.common.setup_i18n()
    import unittest

    sys.argv.append("discover")
    sys.argv.append("tests")
    unittest.TestProgram(module=None)
Esempio n. 30
0
    #opener = urllib2.build_opener(h)
    #urllib2.install_opener(opener)

    #httplib.HTTPConnection.debuglevel = 1

    # Some ugly hackery here... want to run tests multiple times w/ dif
    #  configs, so we'll just monkeypatch sys.exit
    def nexit(code):
        pass

    oexit = sys.exit
    sys.exit = nexit

    testconf = GeoIQTestConf()

    for (name, conf) in testconf.conf["suite"].iteritems():
        # if name != "geocommons.com (shoutis)": continue

        rout.write("/* suite %s ... */\n" % (name))
        GeoIQTestConf.use_suite(name)
        tr = FuncTestRunner()

        ut.TestProgram(testRunner=tr)

    sys.exit = oexit
    sys.stdout.write("testResults(")
    sys.stdout.write(
        json.dumps(list(FuncTestRunner.alltests), ensure_ascii=True))
    sys.stdout.write(");")
    sys.exit(all(t["status"] == "success" for t in FuncTestRunner.alltests))