Exemplo n.º 1
0
        "Testing default initializer"
        text = """
        ABC3 = (1, 2, 3)
        1: ABC1* = ABC
        1: ABC2* = ABC1 and ABC2
        """
        data = self.params[1]
        eng  = Model( mode='plde', text=text )
        eng.initialize( missing=helper.initializer( data, default=(1,1,1) ) )

        for node in 'ABC1 ABC2'.split():
            self.assertEqual( eng.start[node], (1, 1, 1) )
        
        self.assertEqual( eng.start['ABC3'], (1.0, 2.0, 3.0) )


def get_suite():
    suite = unittest.TestLoader().loadTestsFromTestCase( HelperTest )
    return suite

if __name__ == '__main__':
    unittest.TextTestRunner( verbosity=2 ).run( get_suite() )  

    fname  = 'test-params.csv'
        
    # this contains all parameters
    params = helper.read_parameters( fname )

    #print params[0].PIC['conc']

Exemplo n.º 2
0
def test_runner(root_tmpdir, resultclass, failfast=False):
    resultclass.root_tmpdir = root_tmpdir
    return unittest.TextTestRunner(verbosity=255, resultclass=resultclass, failfast=failfast)
Exemplo n.º 3
0
if tests.countTestCases() == 0:
    print("%s had no unit tests" % parsed.pyfile)
    sys.exit(1)

all_tests = {}
for test in tests:
    for t in test:
        all_tests[str(t)] = t

if parsed.test:
    # A test name was passed in, so just try to run it.
    if parsed.test in all_tests:
        test_to_run = all_tests[parsed.test]
        # Apparently the setupClass/tearDownClass aren't called when running an individual test
        test_to_run.setUpClass()
        runner = unittest.TextTestRunner(verbosity=parsed.verbosity, buffer=parsed.buffer)
        results = runner.run(test_to_run)
        test_to_run.tearDownClass()
        sys.exit(int(not results.wasSuccessful()))
    else:
        print("%s not found in %s" % (parsed.test, parsed.pyfile))
        sys.exit(1)
else:
    # No test name passed in. Break out each test and run them in their own process
    final_code = 0
    for name in all_tests.keys():
        cmd = [__file__, "-f", parsed.pyfile, "-v", str(parsed.verbosity), "-t", name]
        if parsed.buffer:
            cmd.append("-b")
        ret = subprocess.call(cmd)
        if ret != 0:
Exemplo n.º 4
0
from com.db.conf import Conf
from com.db.library import Log
from com.db.library.Common import LoginApp
from com.db.library.Spider import Element


class TestCaseForgetPassword(TestCase):
    def setUp(self):
        self.driver = LoginApp().sysLogin()
        Conf.DRIVER = self.driver
        self.driver.implicitly_wait(30)

    def test_case_001_forget_password(self):
        Conf.CASE_NAME = "test_case_001_forget_password"

        Log.start_test(Conf.CASE_NAME)

        Element.find_element(self.driver, By.CLASS_NAME,
                             u'pass-fgtpwd').click()
        Log.stop_test()

    def tearDown(self):
        self.driver.quit()


if __name__ == "__main__":
    suite = unittest.TestSuite()
    suite.addTest(TestCaseForgetPassword("test_case_001_forget_password"))
    unittest.TextTestRunner().run(suite)
Exemplo n.º 5
0
def test():
    test = unittest.TestLoader().discover('project/tests', pattern='test_*.py')
    result = unittest.TextTestRunner(verbosity=2).run(test)
    if result.wasSuccessful():
        return 0
    return 1
Exemplo n.º 6
0
def runTests():
    suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestStringMethods)
    unittest.TextTestRunner(verbosity=2, failfast=True).run(suite)
Exemplo n.º 7
0
 def test(count):
     """运行单元测试"""
     import unittest
     test_suite = unittest.TestLoader().discover(('tests'))
     unittest.TextTestRunner(verbosity=count).run(test_suite)
def main():
    pytests = pysuite()
    unittest.TextTestRunner(verbosity=2).run(pytests)
    return
Exemplo n.º 9
0
def test():
    runner = unittest.TextTestRunner()
    runner.run(suite())
Exemplo n.º 10
0
def run_all():
    # demo_test = unittest.TestLoader().loadTestsFromTestCase(PkiCatalogTests)
    unittest.TextTestRunner(verbosity=3, stream=sys.stdout).run(suite())
Exemplo n.º 11
0
def run_subset():
    unittest.TextTestRunner(verbosity=3, stream=sys.stdout).run(suiteSubset())
Exemplo n.º 12
0
    parser.add_argument(
        '--testdata',
        help=
        "test data directory (default is testdata folder within script directory)"
    )

    #### Parse Arguments
    args = parser.parse_args()
    global test_dir

    if args.testdata:
        test_dir = os.path.abspath(args.testdata)
    else:
        test_dir = os.path.join(script_dir, 'testdata')

    if not os.path.isdir(test_dir):
        parser.error("Test data folder does not exist: {}".format(test_dir))

    test_cases = [
        TestMosaicImageInfo, TestMosaicDataValues, TestMosaicCutlinesShp,
        TestMosaicTilesShp, TestMiscFunctions
    ]

    suites = []
    for test_case in test_cases:
        suite = unittest.TestLoader().loadTestsFromTestCase(test_case)
        suites.append(suite)

    alltests = unittest.TestSuite(suites)
    unittest.TextTestRunner(verbosity=2).run(alltests)
Exemplo n.º 13
0
def main():
    suite = unittest.TestLoader().loadTestsFromTestCase(SolutionTester)
    unittest.TextTestRunner(verbosity=2).run(suite)
def main():
    pytests = pysuite()
    alltests = unittest.TestSuite( (pytests, ) )
    unittest.TextTestRunner(verbosity=2).run(alltests)
    return
Exemplo n.º 15
0
def _run_complete_suite():
    from exactly_lib_test.cli_default.test_resources.internal_main_program_runner import \
        main_program_runner_with_default_setup__in_same_process

    unittest.TextTestRunner().run(complete_suite_for(main_program_runner_with_default_setup__in_same_process()))
Exemplo n.º 16
0
## @file
# Unit tests for C based BaseTools
#
#  Copyright (c) 2008, Intel Corporation. All rights reserved.<BR>
#
#  SPDX-License-Identifier: BSD-2-Clause-Patent
#

##
# Import Modules
#
import os
import sys
import unittest

import TianoCompress
modules = (TianoCompress, )


def TheTestSuite():
    suites = list(map(lambda module: module.TheTestSuite(), modules))
    return unittest.TestSuite(suites)


if __name__ == '__main__':
    allTests = TheTestSuite()
    unittest.TextTestRunner().run(allTests)
Exemplo n.º 17
0
def run_test(TestCase):
    import cStringIO
    stream = cStringIO.StringIO()
    suite = unittest.TestLoader().loadTestsFromTestCase(TestCase)
    unittest.TextTestRunner(stream=stream, verbosity=2).run(suite)
    return stream.getvalue()
Exemplo n.º 18
0
        cleartext = BlockIo.Helper.decrypt(ciphertext, key)
        self.assertEqual(cleartext, clear.encode('utf-8'))

class TestKeys(unittest.TestCase):
    def setUp(self):
        self.priv = "6b0e34587dece0ef042c4c7205ce6b3d4a64d0bc484735b9325f7971a0ead963"
        self.passphrase = "deadbeeffeedface";

    def test_key_init(self):
        key = BlockIo.Key(unhexlify(self.priv))
        self.assertEqual(key.pubkey_hex(), b'029c06f988dc6b44696e002e8abf496a13c73c2f1db3bde2dfb69be129f3711b01')

    def test_from_passphrase(self):
        key = BlockIo.Key.from_passphrase(unhexlify(self.passphrase))
        self.assertEqual(key.pubkey_hex(), b'029023d9738c623cdd7e5fdd0f41666accb82f21df5d27dc5ef07040f7bdc5d9f5')

basicTest = unittest.TestLoader().loadTestsFromTestCase(TestBasicInteractions)
witdrawTest = unittest.TestLoader().loadTestsFromTestCase(TestWithdrawInteractions)
sigTest = unittest.TestLoader().loadTestsFromTestCase(TestDeterministicSignatures)
helperTest = unittest.TestLoader().loadTestsFromTestCase(TestHelpers)
keyTest = unittest.TestLoader().loadTestsFromTestCase(TestKeys)

# run dat shiznit
print("TESTING BLOCK-IO, api: v{av}; client: v{cv}".format(av=block_io.version, cv=block_io.clientVersion))
unittest.TextTestRunner(verbosity=2).run(helperTest)
unittest.TextTestRunner(verbosity=2).run(keyTest)
unittest.TextTestRunner(verbosity=2).run(sigTest)
unittest.TextTestRunner(verbosity=2).run(basicTest)
unittest.TextTestRunner(verbosity=2).run(witdrawTest)

Exemplo n.º 19
0
            except OSError:
                pass

        # See what pbap-client sees.
        self.assertIn('Creating Session', lines)
        self.assertIn('--- Select Phonebook PB ---', lines)
        self.assertIn('--- GetSize ---', lines)
        self.assertIn('Size = 0', lines)
        self.assertIn('--- List vCard ---', lines)
        self.assertIn(
            'Transfer /org/bluez/obex/client/session0/transfer0 complete',
            lines)
        self.assertIn(
            'Transfer /org/bluez/obex/client/session0/transfer1 complete',
            lines)
        self.assertIn(
            'Transfer /org/bluez/obex/client/session0/transfer2 complete',
            lines)
        self.assertIn(
            'Transfer /org/bluez/obex/client/session0/transfer3 complete',
            lines)
        self.assertIn('FINISHED', lines)

        self.assertNotIn('ERROR', lines)


if __name__ == '__main__':
    # avoid writing to stderr
    unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout,
                                                     verbosity=2))
Exemplo n.º 20
0
        def test_detect_empty_integer(self):
            with self.assertRaisesRegexp(DecodingException,
                                         "^Empty integer"):
                bdecode(b"l4:spamiee")

        def test_detect_leading_zeroes(self):
            # Detect leading zero
            with self.assertRaisesRegexp(DecodingException,
                                         "^Leading zeroes"):
                bdecode(b"i01e", strict=True)

            # Detect leading zero of negative number
            with self.assertRaisesRegexp(DecodingException,
                                         "^Leading zeroes"):
                bdecode(b"i-01e", strict=True)

            # Detect negative zero
            with self.assertRaisesRegexp(DecodingException,
                                         "negative zero"):
                bdecode(b"i-0e", strict=True)

            # However, the zero itself must be accepted...
            self.assertEquals(0, bdecode(b"i0e", strict=True))

        def test_bad_sized_string(self):
            with self.assertRaises(DecodingException):
                bdecode(b"l12:normalstring-5:badstringe")

    unittest.main(testRunner=unittest.TextTestRunner(verbosity=2), exit=False)

Exemplo n.º 21
0
def test():
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner().run(tests)
Exemplo n.º 22
0
                dest.write(bytes(score, 'utf-8'))
        dest.write(b'\n')

    if summary_file is not None:
        avg_quality = score_sum / base_count if base_count > 0 else None
        summary = dict(base_count=base_count, avg_quality=avg_quality)
        summary_writer = csv.DictWriter(summary_file,
                                        ['avg_quality', 'base_count'],
                                        lineterminator=os.linesep)
        summary_writer.writeheader()
        summary_writer.writerow(summary)


if __name__ == '__main__':
    args = parseArgs()

    censor(src=args.original_fastq,
           bad_cycles_reader=csv.DictReader(args.bad_cycles_csv),
           dest=args.censored_fastq,
           use_gzip=not args.unzipped)
elif __name__ == '__live_coding__':
    import unittest
    from micall.tests.censor_fastq_test import CensorTest

    suite = unittest.TestSuite()
    suite.addTest(CensorTest("testSummaryEmpty"))
    test_results = unittest.TextTestRunner().run(suite)

    print(test_results.errors)
    print(test_results.failures)
Exemplo n.º 23
0
                for i,(text,pageNumber,key) in enumerate(TOC):
                    yb = y - i*leading      #baseline
                    canv.drawString(x,yb,text)
                    canv.drawRightString(x1,y-i*leading,str(pageNumber))
                canv.endForm()
                canv.restoreState()

        headerStyle = makeHeaderStyle(0)
        S = [Spacer(0,180),UseForm('TOC')]
        RT = 'STARTUP COMPUTERS BLAH BUZZWORD STARTREK PRINTING PYTHON CHOMSKY'.split()
        for i in range(chapters):
            S.append(PageBreak())
            S.append(HParagraph(i,'This is chapter %d' % (i+1), headerStyle))
            txt = xmlEscape(randomtext.randomText(RT[i*13 % len(RT)], 15))
            para = Paragraph(txt, makeBodyStyle())
            S.append(para)

        S.append(MakeForm('TOC'))

        doc = MyDocTemplate(outputfile('test_platypus_toc_simple.pdf'))
        doc.build(S)

def makeSuite():
    return makeSuiteForClasses(TocTestCase)


#noruntests
if __name__ == "__main__":
    unittest.TextTestRunner().run(makeSuite())
    printLocation()
Exemplo n.º 24
0
...     def test_skipunless(self):
...         raise RuntimeError
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSkip)
>>> unittest.TextTestRunner(verbosity=2).run(suite)
test_always_run (__main__.TestSkip) ... ok
test_always_skip (__main__.TestSkip) ... skipped 'always skip this test'
test_skipif (__main__.TestSkip) ... skipped 'demo skipIf'
test_skipunless (__main__.TestSkip) ... skipped 'demo skipUnless'

----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK (skipped=3)
Monolithic Test
>>> from __future__ import print_function
>>> import unittest
>>> class Monolithic(unittest.TestCase):
...     def step1(self):
...         print('step1')
...     def step2(self):
...         print('step2')
...     def step3(self):
...         print('step3')
...     def _steps(self):
...         for attr in sorted(dir(self)):
...             if not attr.startswith('step'):
...                 continue
...             yield attr
...     def test_foo(self):
...         for _s in self._steps():
...             try:
...                 getattr(self, _s)()
...             except Exception as e:
...                 self.fail('{} failed({})'.format(attr, e))
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(Monolithic)
>>> unittest.TextTestRunner().run(suite)
step1
step2
step3
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
<unittest.runner.TextTestResult run=1 errors=0 failures=0>
Cross-module variables to Test files
test_foo.py

from __future__ import print_function

import unittest

print(conf)

class TestFoo(unittest.TestCase):
    def test_foo(self):
        print(conf)

    @unittest.skipIf(conf.isskip==True, "skip test")
    def test_skip(self):
        raise RuntimeError
test_bar.py

from __future__ import print_function

import unittest
import __builtin__

if __name__ == "__main__":
    conf = type('TestConf', (object,), {})
    conf.isskip = True

    # make a cross-module variable
    __builtin__.conf = conf
    module = __import__('test_foo')
    loader = unittest.TestLoader()
    suite = loader.loadTestsFromTestCase(module.TestFoo)
    unittest.TextTestRunner(verbosity=2).run(suite)
output:

$ python test_bar.py
<class '__main__.TestConf'>
test_foo (test_foo.TestFoo) ... <class '__main__.TestConf'>
ok
test_skip (test_foo.TestFoo) ... skipped 'skip test'

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK (skipped=1)
skip setup & teardown when the test is skipped
>>> from __future__ import print_function
>>> import unittest
>>> class TestSkip(unittest.TestCase):
...     def setUp(self):
...         print("setUp")
...     def tearDown(self):
...         print("tearDown")
...     @unittest.skip("skip this test")
...     def test_skip(self):
...         raise RuntimeError
...     def test_not_skip(self):
...         self.assertTrue(True)
...
>>> suite = unittest.TestLoader().loadTestsFromTestCase(TestSkip)
>>> unittest.TextTestRunner(verbosity=2).run(suite)
test_not_skip (__main__.TestSkip) ... setUp
tearDown
ok
test_skip (__main__.TestSkip) ... skipped 'skip this test'

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK (skipped=1)
Re-using old test code
>>> from __future__ import print_function
>>> import unittest
>>> def old_func_test():
...     assert "Hello" == "Hello"
...
>>> def old_func_setup():
...     print("setup")
...
>>> def old_func_teardown():
...     print("teardown")
...
>>> testcase = unittest.FunctionTestCase(old_func_test,
...                                      setUp=old_func_setup,
...                                      tearDown=old_func_teardown)
>>> suite = unittest.TestSuite([testcase])
>>> unittest.TextTestRunner().run(suite)
setup
teardown
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
<unittest.runner.TextTestResult run=1 errors=0 failures=0>
Testing your document is right
"""
This is an example of doctest

>>> fib(10)
55
"""

def fib(n):
""" This function calculate fib number.

Example:

    >>> fib(10)
    55
    >>> fib(-1)
    Traceback (most recent call last):
    ...
    ValueError
"""
if n < 0:
    raise ValueError('')
return 1 if n<=2 else fib(n-1) + fib(n-2)

if __name__ == "__main__":
    import doctest
    doctest.testmod()
output:

$ python demo_doctest.py -v
Trying:
fib(10)
Expecting:
55
ok
Trying:
fib(10)
Expecting:
55
ok
Trying:
fib(-1)
Expecting:
Traceback (most recent call last):
...
ValueError
ok
2 items passed all tests:
1 tests in __main__
2 tests in __main__.fib
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
Re-using doctest to unittest
import unittest
import doctest

"""
This is an example of doctest

>>> fib(10)
55
"""

def fib(n):
    """ This function calculate fib number.

    Example:

        >>> fib(10)
        55
        >>> fib(-1)
        Traceback (most recent call last):
            ...
        ValueError
    """
    if n < 0:
        raise ValueError('')
    return 1 if n<=2 else fib(n-1) + fib(n-2)

if __name__ == "__main__":
    finder = doctest.DocTestFinder()
    suite = doctest.DocTestSuite(test_finder=finder)
    unittest.TextTestRunner(verbosity=2).run(suite)
output:

fib (__main__)
Doctest: __main__.fib ... ok

----------------------------------------------------------------------
Ran 1 test in 0.023s

OK
Customize test report
from unittest import (
        TestCase,
        TestLoader,
        TextTestResult,
        TextTestRunner)

from pprint import pprint
import unittest
import os

OK = 'ok'
FAIL = 'fail'
ERROR = 'error'
SKIP = 'skip'

class JsonTestResult(TextTestResult):

    def __init__(self, stream, descriptions, verbosity):
        super_class = super(JsonTestResult, self)
        super_class.__init__(stream, descriptions, verbosity)

        # TextTestResult has no successes attr
        self.successes = []

    def addSuccess(self, test):
        # addSuccess do nothing, so we need to overwrite it.
        super(JsonTestResult, self).addSuccess(test)
        self.successes.append(test)

    def json_append(self, test, result, out):
        suite = test.__class__.__name__
        if suite not in out:
            out[suite] = {OK: [], FAIL: [], ERROR:[], SKIP: []}
        if result is OK:
            out[suite][OK].append(test._testMethodName)
        elif result is FAIL:
            out[suite][FAIL].append(test._testMethodName)
        elif result is ERROR:
            out[suite][ERROR].append(test._testMethodName)
        elif result is SKIP:
            out[suite][SKIP].append(test._testMethodName)
        else:
            raise KeyError("No such result: {}".format(result))
        return out

    def jsonify(self):
        json_out = dict()
        for t in self.successes:
            json_out = self.json_append(t, OK, json_out)

        for t, _ in self.failures:
            json_out = self.json_append(t, FAIL, json_out)

        for t, _ in self.errors:
            json_out = self.json_append(t, ERROR, json_out)

        for t, _ in self.skipped:
            json_out = self.json_append(t, SKIP, json_out)

        return json_out

class TestSimple(TestCase):

    def test_ok_1(self):
        foo = True
        self.assertTrue(foo)

    def test_ok_2(self):
        bar = True
        self.assertTrue(bar)

    def test_fail(self):
        baz = False
        self.assertTrue(baz)

    def test_raise(self):
        raise RuntimeError

    @unittest.skip("Test skip")
    def test_skip(self):
        raise NotImplementedError

if __name__ == '__main__':
    # redirector default output of unittest to /dev/null
    with open(os.devnull, 'w') as null_stream:
        # new a runner and overwrite resultclass of runner
        runner = TextTestRunner(stream=null_stream)
        runner.resultclass = JsonTestResult

        # create a testsuite
        suite = TestLoader().loadTestsFromTestCase(TestSimple)

        # run the testsuite
        result = runner.run(suite)

        # print json output
        pprint(result.jsonify())
output:

$ python test.py
{'TestSimple': {'error': ['test_raise'],
                'fail': ['test_fail'],
                'ok': ['test_ok_1', 'test_ok_2'],
                'skip': ['test_skip']}}
Mock - using @patch substitute original method
# python-3.3 or above

>>> from unittest.mock import patch
>>> import os
>>> def fake_remove(path, *a, **k):
...     print("remove done")
...
>>> @patch('os.remove', fake_remove)
... def test():
...     try:
...         os.remove('%$!?&*') # fake os.remove
...     except OSError as e:
...         print(e)
...     else:
...         print('test success')
...
>>> test()
remove done
test success
Note
Without mock, above test will always fail.

>>> import os
>>> def test():
...     try:
...         os.remove('%$!?&*')
...     except OSError as e:
...         print(e)
...     else:
...         print('test success')
...
>>> test()
[Errno 2] No such file or directory: '%$!?&*'
What with unittest.mock.patch do?
from unittest.mock import patch
import os

PATH = '$@!%?&'

def fake_remove(path):
    print("Fake remove")


class SimplePatch:

    def __init__(self, target, new):
        self._target = target
        self._new = new

    def get_target(self, target):
        target, attr = target.rsplit('.', 1)
        getter = __import__(target)
        return getter, attr

    def __enter__(self):
        orig, attr = self.get_target(self._target)
        self.orig, self.attr = orig, attr
        self.orig_attr = getattr(orig, attr)
        setattr(orig, attr, self._new)
        return self._new

    def __exit__(self, *exc_info):
        setattr(self.orig, self.attr, self.orig_attr)
        del self.orig_attr


print('---> inside unittest.mock.patch scope')
with patch('os.remove', fake_remove):
    os.remove(PATH)

print('---> inside simple patch scope')
with SimplePatch('os.remove', fake_remove):
    os.remove(PATH)

print('---> outside patch scope')
try:
    os.remove(PATH)
except OSError as e:
    print(e)
output:

$ python3 simple_patch.py
---> inside unittest.mock.patch scope
Fake remove
---> inside simple patch scope
Fake remove
---> outside patch scope
[Errno 2] No such file or directory: '$@!%?&'
Mock - substitute open
>>> import urllib
>>> from unittest.mock import patch, mock_open
>>> def send_req(url):
...     with urllib.request.urlopen(url) as f:
...         if f.status == 200:
...             return f.read()
...         raise urllib.error.URLError
...
>>> fake_html = b'<html><h1>Mock Content</h1></html>'
>>> mock_urlopen = mock_open(read_data=fake_html)
>>> ret = mock_urlopen.return_value
>>> ret.status = 200
>>> @patch('urllib.request.urlopen', mock_urlopen)
... def test_send_req_success():
...     try:
...         ret = send_req('http://www.mockurl.com')
...         assert ret == fake_html
...     except Exception as e:
...         print(e)
...     else:
...         print('test send_req success')
...
>>> test_send_req_success()
test send_req success
>>> ret = mock_urlopen.return_value
>>> ret.status = 404
>>> @patch('urllib.request.urlopen', mock_urlopen)
... def test_send_req_fail():
...     try:
...         ret = send_req('http://www.mockurl.com')
...         assert ret == fake_html
...     except Exception as e:
...         print('test fail success')
...
>>> test_send_req_fail()
test fail success
Exemplo n.º 25
0
gobject.threads_init()


SKIP_FILES = ['runtests',
              'test_mainloop',      # no os.fork on windows
              'test_subprocess']    # blocks on testChildWatch


if __name__ == '__main__':
    testdir = os.path.split(os.path.abspath(__file__))[0]
    os.chdir(testdir)

    def gettestnames():
        files = glob.glob('*.py')
        names = map(lambda x: x[:-3], files)
        map(names.remove, SKIP_FILES)
        return names

    suite = unittest.TestSuite()
    loader = unittest.TestLoader()

    for name in gettestnames():
        try:
            suite.addTest(loader.loadTestsFromName(name))
        except Exception, e:
            print 'Could not load %s: %s' % (name, e)

    testRunner = unittest.TextTestRunner()
    testRunner.verbosity = 2
    testRunner.run(suite)
Exemplo n.º 26
0
def fib(n):
""" This function calculate fib number.

Example:

    >>> fib(10)
    55
    >>> fib(-1)
    Traceback (most recent call last):
    ...
    ValueError
"""
if n < 0:
    raise ValueError('')
return 1 if n<=2 else fib(n-1) + fib(n-2)

if __name__ == "__main__":
    import doctest
    doctest.testmod()
output:

$ python demo_doctest.py -v
Trying:
fib(10)
Expecting:
55
ok
Trying:
fib(10)
Expecting:
55
ok
Trying:
fib(-1)
Expecting:
Traceback (most recent call last):
...
ValueError
ok
2 items passed all tests:
1 tests in __main__
2 tests in __main__.fib
3 tests in 2 items.
3 passed and 0 failed.
Test passed.
Re-using doctest to unittest
import unittest
import doctest

"""
This is an example of doctest

>>> fib(10)
55
"""

def fib(n):
    """ This function calculate fib number.

    Example:

        >>> fib(10)
        55
        >>> fib(-1)
        Traceback (most recent call last):
            ...
        ValueError
    """
    if n < 0:
        raise ValueError('')
    return 1 if n<=2 else fib(n-1) + fib(n-2)

if __name__ == "__main__":
    finder = doctest.DocTestFinder()
    suite = doctest.DocTestSuite(test_finder=finder)
    unittest.TextTestRunner(verbosity=2).run(suite)
output:

fib (__main__)
Doctest: __main__.fib ... ok

----------------------------------------------------------------------
Ran 1 test in 0.023s

OK
Customize test report
from unittest import (
        TestCase,
        TestLoader,
        TextTestResult,
        TextTestRunner)

from pprint import pprint
import unittest
import os

OK = 'ok'
FAIL = 'fail'
ERROR = 'error'
SKIP = 'skip'

class JsonTestResult(TextTestResult):

    def __init__(self, stream, descriptions, verbosity):
        super_class = super(JsonTestResult, self)
        super_class.__init__(stream, descriptions, verbosity)

        # TextTestResult has no successes attr
        self.successes = []

    def addSuccess(self, test):
        # addSuccess do nothing, so we need to overwrite it.
        super(JsonTestResult, self).addSuccess(test)
        self.successes.append(test)

    def json_append(self, test, result, out):
        suite = test.__class__.__name__
        if suite not in out:
            out[suite] = {OK: [], FAIL: [], ERROR:[], SKIP: []}
        if result is OK:
            out[suite][OK].append(test._testMethodName)
        elif result is FAIL:
            out[suite][FAIL].append(test._testMethodName)
        elif result is ERROR:
            out[suite][ERROR].append(test._testMethodName)
        elif result is SKIP:
            out[suite][SKIP].append(test._testMethodName)
        else:
            raise KeyError("No such result: {}".format(result))
        return out

    def jsonify(self):
        json_out = dict()
        for t in self.successes:
            json_out = self.json_append(t, OK, json_out)

        for t, _ in self.failures:
            json_out = self.json_append(t, FAIL, json_out)

        for t, _ in self.errors:
            json_out = self.json_append(t, ERROR, json_out)

        for t, _ in self.skipped:
            json_out = self.json_append(t, SKIP, json_out)

        return json_out

class TestSimple(TestCase):

    def test_ok_1(self):
        foo = True
        self.assertTrue(foo)

    def test_ok_2(self):
        bar = True
        self.assertTrue(bar)

    def test_fail(self):
        baz = False
        self.assertTrue(baz)

    def test_raise(self):
        raise RuntimeError

    @unittest.skip("Test skip")
    def test_skip(self):
        raise NotImplementedError

if __name__ == '__main__':
    # redirector default output of unittest to /dev/null
    with open(os.devnull, 'w') as null_stream:
        # new a runner and overwrite resultclass of runner
        runner = TextTestRunner(stream=null_stream)
        runner.resultclass = JsonTestResult

        # create a testsuite
        suite = TestLoader().loadTestsFromTestCase(TestSimple)

        # run the testsuite
        result = runner.run(suite)

        # print json output
        pprint(result.jsonify())
output:

$ python test.py
{'TestSimple': {'error': ['test_raise'],
                'fail': ['test_fail'],
                'ok': ['test_ok_1', 'test_ok_2'],
                'skip': ['test_skip']}}
Mock - using @patch substitute original method
# python-3.3 or above

>>> from unittest.mock import patch
>>> import os
>>> def fake_remove(path, *a, **k):
...     print("remove done")
...
>>> @patch('os.remove', fake_remove)
... def test():
...     try:
...         os.remove('%$!?&*') # fake os.remove
...     except OSError as e:
...         print(e)
...     else:
...         print('test success')
...
>>> test()
remove done
test success
Note
Without mock, above test will always fail.

>>> import os
>>> def test():
...     try:
...         os.remove('%$!?&*')
...     except OSError as e:
...         print(e)
...     else:
...         print('test success')
...
>>> test()
[Errno 2] No such file or directory: '%$!?&*'
What with unittest.mock.patch do?
from unittest.mock import patch
import os

PATH = '$@!%?&'

def fake_remove(path):
    print("Fake remove")


class SimplePatch:

    def __init__(self, target, new):
        self._target = target
        self._new = new

    def get_target(self, target):
        target, attr = target.rsplit('.', 1)
        getter = __import__(target)
        return getter, attr

    def __enter__(self):
        orig, attr = self.get_target(self._target)
        self.orig, self.attr = orig, attr
        self.orig_attr = getattr(orig, attr)
        setattr(orig, attr, self._new)
        return self._new

    def __exit__(self, *exc_info):
        setattr(self.orig, self.attr, self.orig_attr)
        del self.orig_attr


print('---> inside unittest.mock.patch scope')
with patch('os.remove', fake_remove):
    os.remove(PATH)

print('---> inside simple patch scope')
with SimplePatch('os.remove', fake_remove):
    os.remove(PATH)

print('---> outside patch scope')
try:
    os.remove(PATH)
except OSError as e:
    print(e)
output:

$ python3 simple_patch.py
---> inside unittest.mock.patch scope
Fake remove
---> inside simple patch scope
Fake remove
---> outside patch scope
[Errno 2] No such file or directory: '$@!%?&'
Mock - substitute open
>>> import urllib
>>> from unittest.mock import patch, mock_open
>>> def send_req(url):
...     with urllib.request.urlopen(url) as f:
...         if f.status == 200:
...             return f.read()
...         raise urllib.error.URLError
...
>>> fake_html = b'<html><h1>Mock Content</h1></html>'
>>> mock_urlopen = mock_open(read_data=fake_html)
>>> ret = mock_urlopen.return_value
>>> ret.status = 200
>>> @patch('urllib.request.urlopen', mock_urlopen)
... def test_send_req_success():
...     try:
...         ret = send_req('http://www.mockurl.com')
...         assert ret == fake_html
...     except Exception as e:
...         print(e)
...     else:
...         print('test send_req success')
...
>>> test_send_req_success()
test send_req success
>>> ret = mock_urlopen.return_value
>>> ret.status = 404
>>> @patch('urllib.request.urlopen', mock_urlopen)
... def test_send_req_fail():
...     try:
...         ret = send_req('http://www.mockurl.com')
...         assert ret == fake_html
...     except Exception as e:
...         print('test fail success')
...
>>> test_send_req_fail()
test fail success
Exemplo n.º 27
0
    for exp in [1, 7]:
      for mant in [1, 31]:
        try:
          t = CT(exp=exp, mant=mant)
        except ValueError:
          self.fail("CT constructor raised ExceptionType unexpectedly " +
                    "for exp={0}, mant={1}".format(exp, mant))

  def test_invalid_ct_constructions(self):
    def bad(args, kwargs): CT(**kwargs)
    self.assertRaises(ValueError, bad, [], { "exp"  : -1 })
    self.assertRaises(ValueError, bad, [], { "mant" : -1 })
    self.assertRaises(ValueError, bad, [], { "exp"  :  8 })
    self.assertRaises(ValueError, bad, [], { "mant" : 32 })

  def test_ct_conversion_to_int(self):
    self.assertEqual(int(CT(1,1)),   4)
    self.assertEqual(int(CT(2,2)),  32)
    self.assertEqual(int(CT(3,3)), 192)

  def test_byte_generation(self):
    self.assertEqual( bytearray(CT(1, 1))[0], int('00100001', 2))
    self.assertEqual( bytearray(CT(7,31))[0], int('11111111', 2))

  def test_compress(self):
    self.assertEqual(1024, CT.compress(1024).decompress())

if __name__ == '__main__':
  suite = unittest.TestLoader().loadTestsFromTestCase(TestCT)
  unittest.TextTestRunner(verbosity=2).run(suite)
Exemplo n.º 28
0
def test():
    """Run the unit tests."""
    import unittest
    tests = unittest.TestLoader().discover('tests')
    unittest.TextTestRunner(verbosity=2).run(tests)
Exemplo n.º 29
0
            mode = 'solo'
            test_case = args['testcase']
        else:
            parser.print_help()
    else:
        #Make sure user did not attempt to specify a test-case, show help if so.
        if args['testcase'] == None:
            if args['admin']:
                mode = 'admin'
            elif args['dev']:
                mode = 'developer'
            else:
                mode = 'default'
        else:
            #If user didn't specify admin or dev, assume solo mode.
            if not args['admin'] and not args['dev']:
                mode = 'solo'
                test_case = args['testcase']
            else:
                parser.print_help()

    #If the user wants a log, give them a log.
    log = False
    if args['log']:
        log = True

    #Run the test suite.
    runner = unittest.TextTestRunner(verbosity=2)
    test_suite = suite(mode, test_case, log)
    runner.run(test_suite)
Exemplo n.º 30
0
def test_main():
    testsuite = suite()
    runner = unittest.TextTestRunner(sys.stdout, verbosity=2)
    result = runner.run(testsuite)