Example #1
0
def main(argv=sys.argv[1:]):

    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-v",
        "--verbose",
        action="store_true",
        help="Logging is normally set to an INFO level. When this flag " "is used logging is set to DEBUG. ",
    )

    args = parser.parse_args(argv)

    # Configure logging
    logging_level = logging.DEBUG if args.verbose is True else logging.INFO
    logging.basicConfig()
    logging.getLogger().setLevel(logging_level)

    xunit_file = os.path.join(os.environ.get("RIFT_MODULE_TEST"), "restconf_systest.xml")
    nose.runmodule(
        argv=[
            sys.argv[0],
            "--logging-level={}".format(logging.getLevelName(logging_level)),
            "--logging-format={}".format("%(asctime)-15s %(levelname)s %(message)s"),
            "--nocapture",  # display stdout immediately
            "--with-xunit",
            "--xunit-file=%s" % xunit_file,
        ]
    )
Example #2
0
def main():
    """Run test"""
    # Get line
    argv = list(sys.argv)
    # Add configuration
    argv.extend(["--verbosity=2", "--exe", "--nocapture", "--with-nosango"])
    # Run test
    nose.runmodule(argv=argv)
Example #3
0
def run_module(name, file):
    """Run current test cases of the file.

    Args:
        name: __name__ attribute of the file.
        file: __file__ attribute of the file.
    """

    if name == "__main__":

        nose.runmodule(argv=[file, "-vvs", "-x", "--pdb", "--pdb-failure"], exit=False)
Example #4
0
def _run_tests(path):
    """Runs tests on a library located at path"""
    global rx_h5, nucs, npert, G
    rx_h5 = tb.openFile(path, "r")

    nucs = rx_h5.root.transmute_nucs_LL[:]
    npert = len(rx_h5.root.perturbations)
    G = len(rx_h5.root.energy[0]) - 1

    nose.runmodule(__name__, argv=[__file__])

    rx_h5.close()
Example #5
0
    def test(**kwargs):
        """ Run all pylada nose tests

            Does not include some C++ only tests, nor tests that require
            external programs such as vasp. Those should be run via ctest.
        """
        from os.path import dirname
        from nose import runmodule
        return runmodule(dirname(__file__), **kwargs)
Example #6
0
def main():
    """Main routine, executed when this file is run as a script """

    # Create a tempdir, as a subdirectory of the current one, which all tests
    # use for their storage.  By default, it is removed at the end.
    global TESTDIR
    cwd = os.getcwd()
    TESTDIR = tempfile.mkdtemp(prefix="tmp-testdata-", dir=cwd)

    print "Running tests:"
    # This call form is ipython-friendly
    try:
        os.chdir(TESTDIR)
        nose.runmodule(argv=[__file__, "-vvs"], exit=False)
    finally:
        os.chdir(cwd)

    print
    print "Cleanup - removing temp directory:", TESTDIR
    # If you need to debug a problem, comment out the next line that cleans
    # up the temp directory, and you can see in there all temporary files
    # created by the test code
    shutil.rmtree(TESTDIR)

    print """
***************************************************************************
                           TESTS FINISHED
***************************************************************************

If the printout above did not finish in 'OK' but instead says 'FAILED', copy
and send the *entire* output, including the system information below, for help.
We'll do our best to assist you.  You can send your message to the Scipy user
mailing list:

    http://mail.scipy.org/mailman/listinfo/scipy-user

but feel free to also CC directly: Fernando.Perez@berkeley.edu
"""
    sys_info()
Example #7
0
def runmodule(capture=True):
    """A convenience function for running tests in test modules
    """
    import os
    import nose

    env = {
        "NOSE_WITH_HTML_REPORT": "True",
        "NOSE_HTML_OUTPUT_FILE": "/tmp/test-html/index.html",
        "NOSE_WITH_SPECPLUGIN": "True",
    }
    if not capture:
        env["NOSE_NOCAPTURE"] = "1"
    env.update(os.environ)
    return nose.runmodule(env=env)
Example #8
0
def main(args=None):
    """ run tests for module
    """
    options = parse_test_args(args)

    if options.nonose or options.test:
        # Run tests outside of nose.
        module = sys.modules["__main__"]
        functions = inspect.getmembers(module, inspect.isfunction)
        if options.test:
            func = module.__dict__.get("_test_" + options.test)
            if func is None:
                print "No test named _test_%s" % options.test
                print "Known tests are:", [name[6:] for name, func in functions if name.startswith("_test_")]
                sys.exit(1)
            tests = [func]
        else:
            # Run all tests.
            tests = [func for name, func in functions if name.startswith("_test_")]

        TEST_CONFIG["modname"] = "__main__"
        setup_server(virtual_display=False)
        browser = SafeDriver(setup_chrome())
        try:
            for test in tests:
                try:
                    test(browser)
                except SkipTest:
                    pass
        finally:
            if not options.noclose:
                try:
                    browser.quit()
                except WindowsError:
                    # if it already died, calling kill on a defunct process
                    # raises a WindowsError: Access Denied
                    pass
                teardown_server()
    else:
        # Run under nose.
        import nose

        sys.argv.append("--cover-package=openmdao.")
        sys.argv.append("--cover-erase")
        sys.exit(nose.runmodule())
Example #9
0
def runmodule(level=logging.INFO, argv=[]):
    """
    :param argv: optional list of string with additional options passed to nose.run
    see http://nose.readthedocs.org/en/latest/usage.html
    """
    if argv is None:
        return nose.runmodule()

    setlog(level)

    """ ensures stdout is printed after the tests results"""
    import sys
    from io import StringIO

    module_name = sys.modules["__main__"].__file__

    old_stdout = sys.stdout
    sys.stdout = mystdout = StringIO()

    result = nose.run(argv=[sys.argv[0], module_name, "-s", "--nologcapture"] + argv)

    sys.stdout = old_stdout
    print(mystdout.getvalue())
Example #10
0
if __name__ == "__main__":
    import nose
    from must_methods import gself
    import os

    def setup():
        gself.ls = "ls"

    def test_must_equal():
        print "ok"
        print gself.ls
        "sdd", (1).must_equal(1)

    # support print in the test methods
    os.environ["NOSE_NOCAPTURE"] = "1"
    result = nose.runmodule()
Example #11
0
def test_is_4d():
    film = create_random_image(ndim=4)
    assert_true(is_4D(film))
    assert_false(is_3D(film))
    assert_true(is_4D(create_random_image(shape=(64, 64, 64, 1))))


def test_get_shape():
    shape = (61, 62, 63, 64)
    img = create_random_image(shape)
    assert_equal(get_shape(img), shape)

    shape = (34, 45, 65)
    n_scans = 10
    img = [create_random_image(shape) for _ in xrange(n_scans)]
    assert_equal(get_shape(img), tuple(list(shape) + [n_scans]))


def test_get_relative_path():
    assert_equal(get_relative_path("dop/", "dop/rob"), "rob")

    assert_equal(get_relative_path("/toto/titi", "/toto/titi/tata/test.txt"), "tata/test.txt")
    assert_equal(get_relative_path("/toto/titi", "/toto/titi/tata/"), "tata")
    assert_equal(get_relative_path("/toto/titi", "/toto/titI/tato/dada"), None)

    assert_equal(get_relative_path("/toto/titi", "/toto/titi"), "")


# run all tests
nose.runmodule(config=nose.config.Config(verbose=2, nocapture=True))
Example #12
0
from test.util import read_file, loop_dim
from tomopy.misc.morph import *
import numpy as np
from nose.tools import assert_equals
from numpy.testing import assert_array_almost_equal


__author__ = "Doga Gursoy"
__copyright__ = "Copyright (c) 2015, UChicago Argonne, LLC."
__docformat__ = "restructuredtext en"


def test_pad():
    # TODO: Check this.
    # loop_dim(pad, read_file('obj.npy'))
    pass


def test_downsample():
    loop_dim(downsample, read_file("obj.npy"))


def test_upsample():
    loop_dim(upsample, read_file("obj.npy"))


if __name__ == "__main__":
    import nose

    nose.runmodule(exit=False)
Example #13
0
        if np.any(t == 0):
            raise ValueError("Inverse transform can not be calculated for t=0")

        #   Initiate the stepsize
        h = 2 * mpmath.pi / self.n

        c1 = mpmath.mpf("0.5017")
        c2 = mpmath.mpf("0.6407")
        c3 = mpmath.mpf("0.6122")
        c4 = mpmath.mpc("0", "0.2645")
        half = mpmath.mpc("0.5")
        one = mpmath.mpc("1.0")

        theta = (-mpmath.pi + (np.arange(self.n) * one + half) * h)[:, np.newaxis]
        z = self.shift + self.n / t * (c1 * theta / tan(c2 * theta) - c3 + c4 * theta)
        dz = self.n / t * (-c1 * c2 * theta / sin(c2 * theta) ** 2 + c1 / tan(c2 * theta) + c4)
        inv_laplace = (exp(z * t) * self.f(z, *args) * dz).sum(axis=0)
        inv_laplace *= h / (2j * mpmath.pi)

        if len(inv_laplace) == 1:
            return inv_laplace[0].real
        else:
            return np.array([getattr(v, "real") for v in inv_laplace])


if __name__ == "__main__":
    import nose

    nose.runmodule(argv=["nose", "--verbosity=3", "--with-doctest"])
#    nose.runmodule(argv=['nose', '--verbosity=3'])
Example #14
0
        expected = [[576.7], [962.9], [684.7], [848.3], [933.3]]
        result = web.get_data_fred("A09024USA144NNBR", start="1915").ix[:5]
        assert_array_equal(result.values, np.array(expected))

    def test_invalid_series(self):
        name = "NOT A REAL SERIES"
        self.assertRaises(Exception, web.get_data_fred, name)

    def test_fred_multi(self):  # pragma: no cover
        raise nose.SkipTest("buggy as of 2/18/14; maybe a data revision?")
        names = ["CPIAUCSL", "CPALTT01USQ661S", "CPILFESL"]
        start = datetime(2010, 1, 1)
        end = datetime(2013, 1, 27)

        received = web.DataReader(names, "fred", start, end).head(1)
        expected = DataFrame(
            [[217.478, 0.99701529, 220.544]], columns=names, index=[pd.tslib.Timestamp("2010-01-01 00:00:00")]
        )
        expected.index.rename("DATE", inplace=True)
        assert_frame_equal(received, expected, check_less_precise=True)

    def test_fred_multi_bad_series(self):

        names = ["NOTAREALSERIES", "CPIAUCSL", "ALSO FAKE"]
        with tm.assertRaises(RemoteDataError):
            web.DataReader(names, data_source="fred")


if __name__ == "__main__":
    nose.runmodule(argv=[__file__, "-vvs", "-x", "--pdb", "--pdb-failure"], exit=False)  # pragma: no cover
Example #15
0
    References
    ----------
    .. [1] Ba-Te, B., Limin Zhang, and Delwyn G. Fredlund. "A General 
           Air-Phase Permeability Function for Airflow through Unsaturated 
           Soils." In Proceedings of Geofrontiers 2005 Cngress, 
           2961-85. Austin, Tx: ASCE, 2005. doi:10.1061/40787(166)29.
           
    """

    return (1 - Sr) ** 0.5 * (1 - Sr ** (1 / qfit)) ** (2 * qfit)


if __name__ == "__main__":
    import nose

    nose.runmodule(argv=["nose", "--verbosity=3", "--with-doctest", "--doctest-options=+ELLIPSIS"])

    if 0:
        a = SWCC_FredlundAndXing1994(a=3000, n=1.5, m=1, ws=60, correction=1)

        b = SWCC_FredlundAndXing1994(a=200, n=2, m=1, ws=40, correction=1)
        c = SWCC_FredlundAndXing1994(a=10, n=4, m=1, ws=30, correction=1)

        [v.plot_model() for v in [a, b, c]]
        plt.gca().set_xscale("log")
        plt.gca().set_ylim([0, 70])
        plt.gca().grid(which="major", linestyle="-")
        plt.gca().grid(which="minor", linestyle="--")
        plt.show()

    if 0:
Example #16
0
    """
    >>> plt.plot(edges[:-1], squaretg.pdf(edges[:-1], 10), 'r')
    [<matplotlib.lines.Line2D object at 0x06EBFDB0>]
    >>> plt.fill(edges[4:8], squaretg.pdf(edges[4:8], 10), 'r')
    [<matplotlib.patches.Polygon object at 0x0725BA90>]
    >>> plt.show()
    >>> plt.fill_between(edges[4:8], squaretg.pdf(edges[4:8], 10), y2=0, 'r')
    SyntaxError: non-keyword arg after keyword arg (<console>, line 1)
    >>> plt.fill_between(edges[4:8], squaretg.pdf(edges[4:8], 10), 0, 'r')
    Traceback (most recent call last):
    AttributeError: 'module' object has no attribute 'fill_between'
    >>> fig = figure()
    Traceback (most recent call last):
    NameError: name 'figure' is not defined
    >>> ax1 = fig.add_subplot(311)
    Traceback (most recent call last):
    NameError: name 'fig' is not defined
    >>> fig = plt.figure()
    >>> ax1 = fig.add_subplot(111)
    >>> ax1.fill_between(edges[4:8], squaretg.pdf(edges[4:8], 10), 0, 'r')
    Traceback (most recent call last):
    AttributeError: 'AxesSubplot' object has no attribute 'fill_between'
    >>> ax1.fill(edges[4:8], squaretg.pdf(edges[4:8], 10), 0, 'r')
    Traceback (most recent call last):
    """

    import nose

    nose.runmodule(argv=["__main__", "-vvs", "-x"], exit=False)  # ,'--pdb', '--pdb-failure'],
Example #17
0
    assert np.isnan(above), msg + "isf out of bounds - above"


def check_loc_scale(distfn, arg, msg):
    m, v = distfn.stats(*arg)
    loc, scale = 10.0, 10.0
    mt, vt = distfn.stats(loc=loc, scale=scale, *arg)
    assert_equal_inf_nan(m * scale + loc, mt, msg + "mean")
    assert_equal_inf_nan(v * scale * scale, vt, msg + "var")


def check_entropy(distfn, arg, msg):
    ent = distfn.entropy(*arg)
    # print 'Entropy =', ent
    assert not np.isnan(ent), msg + "test Entropy is nan"


def assert_equal_inf_nan(v1, v2, msg):
    assert not np.isnan(v1)
    if not np.isinf(v1):
        npt.assert_almost_equal(v1, v2, decimal=DECIMAL, err_msg=msg + " - finite")
    else:
        assert np.isinf(v2) or np.isnan(v2), msg + " - infinite, v2=%s" % str(v2)


if __name__ == "__main__":
    import nose

    # nose.run(argv=['', __file__])
    nose.runmodule(argv=[__file__, "-s"], exit=False)
Example #18
0
                tm.assert_series_equal(s.drop_duplicates(), original)

                last_base = [False] * len(idx)
                last_base[3] = True
                last_base[5] = True
                expected = Series(last_base, index=idx, name="a")
                tm.assert_series_equal(s.duplicated(take_last=True), expected)
                tm.assert_series_equal(s.drop_duplicates(take_last=True), s[~np.array(last_base)])

                s.drop_duplicates(inplace=True)
                tm.assert_series_equal(s, original)


class TestFloat64HashTable(tm.TestCase):
    def test_lookup_nan(self):
        from pandas.hashtable import Float64HashTable

        xs = np.array([2.718, 3.14, np.nan, -7, 5, 2, 3])
        m = Float64HashTable()
        m.map_locations(xs)
        self.assert_numpy_array_equal(m.lookup(xs), np.arange(len(xs)))


if __name__ == "__main__":
    import nose

    nose.runmodule(
        argv=[__file__, "-vvs", "-x", "--pdb", "--pdb-failure"],
        # '--with-coverage', '--cover-package=pandas.core'],
        exit=False,
    )
Example #19
0
    nose.runmodule(argv=["-s", "--with-doctest"])


########NEW FILE########
__FILENAME__ = test_boxplot
__author__ = "olga"

from matplotlib.testing.decorators import image_comparison
import matplotlib.pyplot as plt
import numpy as np
import prettyplotlib as ppl
import os


@image_comparison(baseline_images=["boxplot"], extensions=["png"])
def test_boxplot():
    # Set the random seed for consistency
    np.random.seed(10)

    data = np.random.randn(8, 4)
    labels = ["A", "B", "C", "D"]

    fig, ax = plt.subplots()
    ppl.boxplot(ax, data, xticklabels=labels)
    # fig.savefig('%s/baseline_images/test_boxplot/boxplot.png' %
    #             os.path.dirname(__file__))


if __name__ == "__main__":
    import nose

    nose.runmodule(argv=["-s", "--with-doctest"])
Example #20
0
    def finish():
        d.callback(None)

    reactor.callLater(0.01, finish)
    return d


test_timeout_ok = deferred(timeout=1.0)(test_timeout_ok)

# The deferred is triggered after the timeout: failure
# @raises(TimeExpired)
# @deferred(timeout=0.1)
def test_timeout_expired():
    d = Deferred()

    def finish():
        d.callback(None)

    reactor.callLater(1.0, finish)
    return d


test_timeout_expired = raises(TimeExpired)(deferred(timeout=0.1)(test_timeout_expired))


if __name__ == "__main__":
    from nose import runmodule

    runmodule()
Example #21
0
    def test_idiv(self):
        v = self.vector(1, 2)
        v /= 0.5
        assert v == (2, 4)


###############################################################################
#                                TestCases
###############################################################################


class CVectorTest(Immutable, TestCase):
    from FGAme.mathutils.cvector import Vec2 as vector


class CVectorMTest(Mutable, TestCase):
    from FGAme.mathutils.cvector import mVec2 as vector


class PyVectorTest(Immutable, TestCase):
    from FGAme.mathutils.vector import Vec2 as vector


class PyVectorMTest(Mutable, TestCase):
    from FGAme.mathutils.vector import mVec2 as vector


if __name__ == "__main__":
    nose.runmodule("__main__")
Example #22
0
    def __init__(self):
        self.identity = mtransforms.IdentityTransform()
        self.identity2 = mtransforms.IdentityTransform()
        # Force use of the more complex composition.
        self.composite = mtransforms.CompositeGenericTransform(self.identity, self.identity2)
        # Check parent -> child links of TransformWrapper.
        self.wrapper = mtransforms.TransformWrapper(self.composite)
        # Check child -> parent links of TransformWrapper.
        self.composite2 = mtransforms.CompositeGenericTransform(self.wrapper, self.identity)


def test_transform():
    obj = TransformBlob()
    pf = pickle.dumps(obj)
    del obj

    obj = pickle.loads(pf)
    # Check parent -> child links of TransformWrapper.
    assert_equal(obj.wrapper._child, obj.composite)
    # Check child -> parent links of TransformWrapper.
    assert_equal([v() for v in obj.wrapper._parents.values()], [obj.composite2])
    # Check input and output dimensions are set as expected.
    assert_equal(obj.wrapper.input_dims, obj.composite.input_dims)
    assert_equal(obj.wrapper.output_dims, obj.composite.output_dims)


if __name__ == "__main__":
    import nose

    nose.runmodule(argv=["-s"])
        model = cls(L=L, M=M, N=N, R=R, precision=sdtype)

        # forward operation
        fun = model.forward
        reffun = ref["forward"]
        s = get_random_oncircle(model.sshape, model.sdtype)
        x = get_random_uniform(model.xshape, model.xydtype)
        y = np.zeros(model.yshape, model.xydtype)
        callable_test = check_equal_reference(fun, reffun, (s, x, y))
        callable_test.description = callable_test.description.format(L, M, N, R, np.dtype(sdtype).str)
        yield callable_test

        # adjoint_x operation
        fun = model.adjoint_x
        reffun = ref["adjoint_x"]
        y = get_random_uniform(model.yshape, model.xydtype)
        s = get_random_oncircle(model.sshape, model.sdtype)
        x = np.zeros(model.xshape, model.xydtype)
        callable_test = check_equal_reference(fun, reffun, (y, s, x))
        callable_test.description = callable_test.description.format(L, M, N, R, np.dtype(sdtype).str)
        yield callable_test


if __name__ == "__main__":
    import nose

    # nose.runmodule(argv=[__file__,'-vvs','--nologcapture',
    #'--stop','--pdb','--pdb-failure'],
    # exit=False)
    nose.runmodule(argv=[__file__, "-vvs", "--nologcapture"], exit=False)
Example #24
0
            "font.family": "sans-serif",
            "font.size": 30,
            "figure.subplot.left": 0.2,
            "lines.markersize": 10,
            "pgf.rcfonts": False,
            "pgf.texsystem": "xelatex",
        }
    )
    rc_sets.append(
        {
            "font.family": "monospace",
            "font.size": 10,
            "figure.subplot.left": 0.1,
            "lines.markersize": 20,
            "pgf.rcfonts": False,
            "pgf.texsystem": "pdflatex",
            "pgf.preamble": [r"\usepackage[utf8x]{inputenc}", r"\usepackage[T1]{fontenc}", r"\usepackage{sfmath}"],
        }
    )

    for i, rc_set in enumerate(rc_sets):
        mpl.rcParams.update(rc_set)
        create_figure()
        compare_figure("pgf_rcupdate%d.pdf" % (i + 1))


if __name__ == "__main__":
    import nose

    nose.runmodule(argv=["-s", "--with-doctest"], exit=False)
Example #25
0
        )

    def test_files_already_exist_exception_none_left(self):
        for file in self.test_files_remove:
            write_file(file)
        assert_raises(
            IOError, check_for_old_output_files, [self.rootname], self.test_dir, self.output_mapping, False, False
        )

    def test_files_already_exist_clean(self):
        for file in self.test_files:
            write_file(file)
        assert check_for_old_output_files([self.rootname], self.test_dir, self.output_mapping, True, False)

    def test_only_good_files_clean(self):
        for file in self.test_files_leave:
            write_file(file)
        assert check_for_old_output_files([self.rootname], self.test_dir, self.output_mapping, True, False)

    def test_only_bad_files_clean(self):
        for file in self.test_files_remove:
            write_file(file)
        assert check_for_old_output_files([self.rootname], self.test_dir, self.output_mapping, True, False)


# ----------------------------------------------------------------------------------------
if __name__ == "__main__":
    import nose

    nose.runmodule(argv=["nose", "--verbosity=2"])
Example #26
0
        cur = self.db.cursor()
        cur.execute(drop_sql)
        sql.write_frame(frame, name="test_table", con=self.db, flavor="mysql")
        stmt = "INSERT INTO test_table VALUES(2.314, -123.1, 1.234, 2.3)"
        self.assertEqual(sql.uquery(stmt, con=self.db), 1)

        try:
            sys.stdout = StringIO()

            self.assertRaises(MySQLdb.ProgrammingError, sql.tquery, "insert into blah values (1)", con=self.db)

            self.assertRaises(
                MySQLdb.ProgrammingError, sql.tquery, "insert into blah values (1)", con=self.db, retry=True
            )
        finally:
            sys.stdout = sys.__stdout__

    def test_keyword_as_column_names(self):
        """
        """
        _skip_if_no_MySQLdb()
        df = DataFrame({"From": np.ones(5)})
        sql.write_frame(df, con=self.db, name="testkeywords", if_exists="replace", flavor="mysql")


if __name__ == "__main__":
    # unittest.main()
    # nose.runmodule(argv=[__file__,'-vvs','-x', '--pdb-failure'],
    #                exit=False)
    nose.runmodule(argv=[__file__, "-vvs", "-x", "--pdb", "--pdb-failure"], exit=False)
    try:
        cv = kfold_cross_validation(ml.KMeansCluster(), X, y, k=10)
    except TypeError:
        assert True
    else:
        assert False, "'kfold_cross_validation' should raise an error when " + "called with an unsupervised predictor."


def test_split_data():

    X = np.ones((12, 3))
    y = np.ones(12)
    X_learn, X_test = split_data(X, frac=2 / 3)
    assert len(X_learn) == 8 and len(X_test) == 4
    X_learn, y_learn, X_test, y_test = split_data(X, y, frac=0.75)
    assert len(X_learn) == 9 and len(X_test) == 3 and len(y_learn) == 9 and len(y_test) == 3

    y = np.ones(11)
    try:
        split_data(X, y)
    except (TypeError, ValueError):
        assert True
    else:
        assert False, "'X' and 'y' have different lengths - " + "an exception should have been raised."


if __name__ == "__main__":
    import nose

    nose.runmodule(argv=[__file__, "-vvs", "-x"], exit=False)
Example #28
0
            self.assertRaises(sqlite3.OperationalError, sql.tquery,
                              'select * from blah', con=self.db, retry=True)
        finally:
            sys.stdout = sys.__stdout__

    def test_uquery(self):
        frame = tm.makeTimeDataFrame()
        sql.write_frame(frame, name='test_table', con=self.db)
        stmt = 'INSERT INTO test_table VALUES(2.314, -123.1, 1.234, 2.3)'
        self.assertEqual(sql.uquery(stmt, con=self.db), 1)

        try:
            sys.stdout = StringIO()

            self.assertRaises(sqlite3.OperationalError, sql.tquery,
                              'insert into blah values (1)', con=self.db)

            self.assertRaises(sqlite3.OperationalError, sql.tquery,
                              'insert into blah values (1)', con=self.db,
                              retry=True)
        finally:
            sys.stdout = sys.__stdout__


if __name__ == '__main__':
    # unittest.main()
    import nose
    # nose.runmodule(argv=[__file__,'-vvs','-x', '--pdb-failure'],
    #                exit=False)
    nose.runmodule(argv=[__file__,'-vvs','-x','--pdb', '--pdb-failure'],
                   exit=False)
Example #29
0
def test_double_raw_string_literal():
    yield check_token, 'r"yo"', ["STRING", 'r"yo"', 0]


def test_single_unicode_literal():
    yield check_token, "u'yo'", ["STRING", "u'yo'", 0]


def test_double_unicode_literal():
    yield check_token, 'u"yo"', ["STRING", 'u"yo"', 0]


def test_single_bytes_literal():
    yield check_token, "b'yo'", ["STRING", "b'yo'", 0]


def test_float_literals():
    cases = ["0.0", ".0", "0.", "1e10", "1.e42", "0.1e42", "0.5e-42", "5E10", "5e+42"]
    for s in cases:
        yield check_token, s, ["NUMBER", s, 0]


def test_ioredir():
    cases = ["2>1", "err>out", "o>", "all>", "e>o", "e>", "out>", "2>&1"]
    for s in cases:
        yield check_tokens_subproc, s, [("IOREDIRECT", s, 2)]


if __name__ == "__main__":
    nose.runmodule()

@cleanup
def test_colorbar_no_mappable():
    _fig, _ax, colorbar = create_figure()
    colorbar.set_mappable(False)
    plt.draw()


@image_comparison(baseline_images=["example1"], extensions=["png"])
def test_colorbar_example1():
    with cbook.get_sample_data("grace_hopper.png") as fp:
        data = np.array(plt.imread(fp))

    fig = plt.figure()
    ax = fig.add_subplot("111", aspect="equal")
    mappable = ax.imshow(data[..., 0], cmap="viridis")
    colorbar = Colorbar(mappable, location="lower left")
    colorbar.set_ticks([0.0, 0.5, 1.0])
    ax.add_artist(colorbar)


if __name__ == "__main__":
    import nose
    import sys

    args = ["-s", "--with-doctest"]
    argv = sys.argv
    argv = argv[:1] + args + argv[1:]
    nose.runmodule(argv=argv, exit=False)