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])
def main(): """The main routine.""" # Parse arguments local_url = 'http://localhost:{}'.format(LOCAL_TEST_PORT) parser = argparse.ArgumentParser(description='Run web-service tests') parser.add_argument( '-e', '--endpoint', dest='endpoint', default='auto', help='Which server to test against.\n' 'auto: {} (server starts automatically)\n' 'local: http://localhost:8080\n' 'prod: https://url-caster.appspot.com\n' 'dev: https://url-caster-dev.appspot.com\n' '*: Other values interpreted literally' .format(local_url)) parser.add_argument('-x', '--experimental', dest='experimental', action='store_true', default=False) args = parser.parse_args() # Setup the endpoint endpoint = args.endpoint server = None if endpoint.lower() == 'auto': endpoint = local_url print 'Starting local server1...', server = subprocess.Popen([ '/usr/bin/python /home/happy/google_appengine/dev_appserver.py', os.path.dirname(__file__), '--port', str(LOCAL_TEST_PORT), '--admin_port', str(LOCAL_TEST_PORT + 1), ], bufsize=1, stderr=subprocess.PIPE, preexec_fn=os.setsid) # Wait for the server to start up while True: line = server.stderr.readline() if 'Unable to bind' in line: print 'Rogue server already running.' return 1 if 'running at: {}'.format(local_url) in line: break print 'done' elif endpoint.lower() == 'local': endpoint = 'http://localhost:8080' elif endpoint.lower() == 'prod': endpoint = 'https://url-caster.appspot.com' elif endpoint.lower() == 'dev': endpoint = 'https://url-caster-dev.appspot.com' PwsTest.HOST = endpoint PwsTest.ENABLE_EXPERIMENTAL = args.experimental # Run the tests try: nose.runmodule() finally: # Teardown the endpoint if server: os.killpg(os.getpgid(server.pid), signal.SIGINT) server.wait() # We should never get here since nose.runmodule will call exit return 0
def main(): """The main routine.""" # Parse arguments local_url = 'http://localhost:{}'.format(LOCAL_TEST_PORT) parser = argparse.ArgumentParser(description='Run web-service tests') parser.add_argument( '-e', '--endpoint', dest='endpoint', default='AUTO', help='Which server to test against.\n' 'AUTO: {} (server starts automatically)\n' 'LOCAL: http://localhost:8080\n' 'PROD: http://url-caster.appspot.com\n' 'DEV: http://url-caster-dev.appspot.com\n' '*: Other values interpreted literally' .format(local_url)) args = parser.parse_args() # Setup the endpoint endpoint = args.endpoint server = None if endpoint == 'AUTO': endpoint = local_url print 'Starting local server...', server = subprocess.Popen([ 'dev_appserver.py', os.path.dirname(__file__), '--port', str(LOCAL_TEST_PORT), '--admin_port', str(LOCAL_TEST_PORT + 1), ], bufsize=1, stderr=subprocess.PIPE, preexec_fn=os.setsid) # Wait for the server to start up while True: line = server.stderr.readline() if 'Unable to bind' in line: print 'Rogue server already running.' return 1 if 'running at: {}'.format(local_url) in line: break print 'done' elif endpoint == 'LOCAL': endpoint = 'http://localhost:8080' elif endpoint == 'PROD': endpoint = 'http://url-caster.appspot.com' elif endpoint == 'DEV': endpoint = 'http://url-caster-dev.appspot.com' PwsTest.HOST = endpoint # Run the tests try: nose.runmodule() finally: # Teardown the endpoint if server: os.killpg(os.getpgid(server.pid), signal.SIGINT) server.wait() # We should never get here since nose.runmodule will call exit return 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()
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)
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)
def runmodule(level=logging.INFO, verbosity=1, 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', '--verbosity=%d'%verbosity, ]+argv ) sys.stdout = old_stdout print(mystdout.getvalue())
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)
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: [email protected] """ sys_info()
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())
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_')] setup_server(virtual_display=False) browser = SafeDriver(setup_chrome()) try: for test in tests: test(browser) finally: if not options.noclose: browser.quit() teardown_server() else: # Run under nose. import nose sys.argv.append('--cover-package=openmdao.') sys.argv.append('--cover-erase') sys.exit(nose.runmodule())
@cleanup def test_determinism(): import os import sys from subprocess import check_call from nose.tools import assert_equal plots = [] for i in range(3): check_call( [ sys.executable, "-R", "-c", "from matplotlib.tests.test_backend_svg " "import _test_determinism;" '_test_determinism("determinism.svg")', ] ) with open("determinism.svg", "rb") as fd: plots.append(fd.read()) os.unlink("determinism.svg") for p in plots[1:]: assert_equal(p, plots[0]) if __name__ == "__main__": import nose nose.runmodule(argv=["-s", "--with-doctest"], exit=False)
from nose.tools import ok_ from goldminer import scrapper # import application packages __author__ = 'Sergey Krushinsky' __copyright__ = "Copyright 2014" __license__ = "Apache" __version__ = "1.0.0" __email__ = "*****@*****.**" class TestDefaultSession(): def __init__(self): self.session = scrapper.create_session() def test_user_agent(self): ua = self.session.headers.get('user-agent') ok_(ua in scrapper.ALT_USER_AGENTS) if __name__ == '__main__': import logging logging.basicConfig( level=logging.DEBUG, datefmt='%Y-%m-%d %H:%M:%S', format='%(asctime)s - %(levelname)-8s - %(message)s', ) nose.runmodule(argv=['-d', '-s', '--verbose'])
import nose import sys print("sys.platform = ", sys.platform) print("sys.version = ", sys.version) if sys.platform.startswith('win'): print("!!! Skipping Tests") print("!!! There are known failures in pyamg 3.0.2 on windows") print("!!! See https://github.com/pyamg/pyamg/issues/168") elif sys.platform == 'darwin' and sys.version.startswith('2.7'): print("!!! Skipping Tests") print("!!! There are known failures in pyamg 3.0.2 on Python 2.7 / OSX") print("!!! See https://github.com/pyamg/pyamg/issues/165") else: config = nose.config.Config(verbosity=2) nose.runmodule('pyamg', config=config)
''' >>> 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'], #,'--pdb', '--pdb-failure'], exit=False)
# Trained on sparse format sparse_classifier = AdaBoostRegressor( base_estimator=CustomSVR(probability=True), random_state=1).fit(X_train_sparse, y_train) # Trained on dense format dense_classifier = dense_results = AdaBoostRegressor( base_estimator=CustomSVR(probability=True), random_state=1).fit(X_train, y_train) # predict sparse_results = sparse_classifier.predict(X_test_sparse) dense_results = dense_classifier.predict(X_test) assert_array_equal(sparse_results, dense_results) # staged_predict sparse_results = sparse_classifier.staged_predict(X_test_sparse) dense_results = dense_classifier.staged_predict(X_test) for sprase_res, dense_res in zip(sparse_results, dense_results): assert_array_equal(sprase_res, dense_res) types = [i.data_type_ for i in sparse_classifier.estimators_] assert all([(t == csc_matrix or t == csr_matrix) for t in types]) if __name__ == "__main__": import nose nose.runmodule()
self.assertTrue(len(dates) > 6) def test_get_call_data(self): with tm.assertRaises(NotImplementedError): self.goog.get_call_data() def test_get_put_data(self): with tm.assertRaises(NotImplementedError): self.goog.get_put_data() def test_get_near_stock_price(self): with tm.assertRaises(NotImplementedError): self.goog.get_near_stock_price() def test_get_forward_data(self): with tm.assertRaises(NotImplementedError): self.goog.get_forward_data([1, 2, 3]) def test_get_all_data(self): with tm.assertRaises(NotImplementedError): self.goog.get_all_data() def test_get_options_data_with_year(self): with tm.assertRaises(NotImplementedError): self.goog.get_options_data(year=2016) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False) # pragma: no cover
return 0. E.value = 2 def test_logp(self): self.B.rand() lp1 = utils.logp_of_set(set([self.A,self.B,self.D])) assert_equal(lp1, self.A.logp+self.B.logp+self.D.logp) def test_ZeroProb(self): self.B.value = -1 for i in xrange(1000): try: utils.logp_of_set(set([self.A,self.B,self.D, self.E])) except: cls, inst, tb = sys.exc_info() assert(cls is ZeroProbability) def test_other_err(self): self.B.rand() for i in xrange(1000): try: utils.logp_of_set(set([self.A,self.B,self.D,self.E])) except: cls, inst, tb = sys.exc_info() assert(cls is RuntimeError) if __name__ == '__main__': C =nose.config.Config(verbosity=1) nose.runmodule(config=C)
yticklabels=LOWERCASE_CHARS[-10:], cmap=red_purple) # fig.savefig( # '%s/baseline_images/test_pcolormesh/pcolormesh_positive_other_cmap.png' % # os.path.dirname(__file__)) @image_comparison(baseline_images=['pcolormesh_lognorm'], extensions=['png']) def test_pcolormesh_lognorm(): np.random.seed(10) x = np.abs(np.random.randn(10, 10)) ppl.pcolormesh(x, norm=LogNorm(vmin=x.min().min(), vmax=x.max().max())) # fig.savefig('%s/baseline_images/test_pcolormesh/test_pcolormesh_lognorm.png' % # os.path.dirname(__file__)) @image_comparison(baseline_images=['pcolormesh_axes'], extensions=['png']) def test_pcolormesh_axes(): np.random.seed(10) x=np.arange(0,100,10) y=np.arange(0,20,2) ppl.pcolormesh(x, y, np.random.randn(10, 10)) # fig.savefig('%s/baseline_images/test_pcolormesh/pcolormesh.png' % # os.path.dirname(__file__)) if __name__ == '__main__': import nose nose.runmodule(argv=['-s', '--with-doctest'])
self.assertTrue(idx.equals(DatetimeIndex(dates, tz="US/Eastern"))) idx = idx.tz_convert("UTC") self.assertTrue(idx.equals(DatetimeIndex(dates, tz="UTC"))) dates = ["2010-12-01 00:00", "2010-12-02 00:00", NaT] idx = DatetimeIndex(dates) idx = idx.tz_localize("US/Pacific") self.assertTrue(idx.equals(DatetimeIndex(dates, tz="US/Pacific"))) idx = idx.tz_convert("US/Eastern") expected = ["2010-12-01 03:00", "2010-12-02 03:00", NaT] self.assertTrue(idx.equals(DatetimeIndex(expected, tz="US/Eastern"))) idx = idx + offsets.Hour(5) expected = ["2010-12-01 08:00", "2010-12-02 08:00", NaT] self.assertTrue(idx.equals(DatetimeIndex(expected, tz="US/Eastern"))) idx = idx.tz_convert("US/Pacific") expected = ["2010-12-01 05:00", "2010-12-02 05:00", NaT] self.assertTrue(idx.equals(DatetimeIndex(expected, tz="US/Pacific"))) idx = idx + np.timedelta64(3, "h") expected = ["2010-12-01 08:00", "2010-12-02 08:00", NaT] self.assertTrue(idx.equals(DatetimeIndex(expected, tz="US/Pacific"))) idx = idx.tz_convert("US/Eastern") expected = ["2010-12-01 11:00", "2010-12-02 11:00", NaT] self.assertTrue(idx.equals(DatetimeIndex(expected, tz="US/Eastern"))) if __name__ == "__main__": nose.runmodule(argv=[__file__, "-vvs", "-x", "--pdb", "--pdb-failure"], exit=False)
# check calling w/ named arguments shape_args = list(shape_args) vals = [meth(x, *shape_args) for meth in meths] npt.assert_(np.all(np.isfinite(vals))) names, a, k = shape_argnames[:], shape_args[:], {} while names: k.update({names.pop(): a.pop()}) v = [meth(x, *a, **k) for meth in meths] npt.assert_array_equal(vals, v) if not 'n' in k.keys(): # `n` is first parameter of moment(), so can't be used as named arg npt.assert_equal(distfn.moment(3, *a, **k), distfn.moment(3, *shape_args)) # unknown arguments should not go through: k.update({'kaboom': 42}) npt.assert_raises(TypeError, distfn.cdf, x, **k) def check_scale_docstring(distfn): if distfn.__doc__ is not None: # Docstrings can be stripped if interpreter is run with -OO npt.assert_('scale' not in distfn.__doc__) if __name__ == "__main__": # nose.run(argv=['', __file__]) nose.runmodule(argv=[__file__,'-s'], exit=False)
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # # POSSIBILITY OF SUCH DAMAGE. # # ######################################################################### from __future__ import (absolute_import, division, print_function, unicode_literals) from tomopy.prep.phase import * from test.util import read_file from numpy.testing import assert_allclose import numpy as np __author__ = "Doga Gursoy" __copyright__ = "Copyright (c) 2015, UChicago Argonne, LLC." __docformat__ = 'restructuredtext en' def test_retrieve_phase(): assert_allclose(retrieve_phase(read_file('proj.npy')), read_file('retrieve_phase.npy'), rtol=1e-6) if __name__ == '__main__': import nose nose.runmodule(exit=False)
frames=iter(range(5))) def test_movie_writer_registry(): ffmpeg_path = mpl.rcParams['animation.ffmpeg_path'] # Not sure about the first state as there could be some writer # which set rcparams #assert_false(animation.writers._dirty) assert_true(len(animation.writers._registered) > 0) animation.writers.list() # resets dirty state assert_false(animation.writers._dirty) mpl.rcParams['animation.ffmpeg_path'] = u"not_available_ever_xxxx" assert_true(animation.writers._dirty) animation.writers.list() # resets assert_false(animation.writers._dirty) assert_false(animation.writers.is_available("ffmpeg")) # something which is guaranteed to be available in path # and exits immediately bin = u"true" if sys.platform != 'win32' else u"where" mpl.rcParams['animation.ffmpeg_path'] = bin assert_true(animation.writers._dirty) animation.writers.list() # resets assert_false(animation.writers._dirty) assert_true(animation.writers.is_available("ffmpeg")) mpl.rcParams['animation.ffmpeg_path'] = ffmpeg_path if __name__ == "__main__": import nose nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
import numpy as np import scipy.spatial np.random.seed(1234) points = np.random.rand(15, 2) * 5 + np.array([130, 40]) hull = cesiumpy.spatial.ConvexHull(points) polyline = hull.get_polyline() expected = [ 130.37690620821488, 41.844120030009876, 132.51541582653905, 40.06884224795341, 133.89987904059402, 41.36296302641321, 134.6657005099126, 43.25689071613289, 134.7906967684185, 44.379663173710476, 133.86413310806188, 44.41320595318058, 131.38232127571547, 44.00936088767509, 130.95759725189447, 43.11054385519916, 130.37690620821488, 41.844120030009876 ] self.assertEqual(polyline.positions.x, expected) hull = scipy.spatial.ConvexHull(points) hull = cesiumpy.spatial.ConvexHull(hull) polyline = hull.get_polyline() self.assertEqual(polyline.positions.x, expected) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
ndmap = NdIndexableMapping(data, dimensions=[self.dim1, self.dim2]) reduced_dims = ['intdim'] reduced_ndmap = ndmap.reindex(reduced_dims) self.assertEqual(reduced_ndmap.dimension_labels, reduced_dims) def test_idxmapping_adddimension(self): ndmap = NdIndexableMapping(self.init_items_1D_list, dimensions=[self.dim1]) ndmap2d = ndmap.add_dimension(self.dim2, 0, 0.5) self.assertEqual(ndmap2d.keys(), [(0.5, 1), (0.5, 5)]) self.assertEqual(ndmap2d.dimensions, [self.dim2, self.dim1]) def test_idxmapping_clone(self): ndmap = NdIndexableMapping(self.init_items_1D_list, dimensions=[self.dim1]) cloned_ndmap = ndmap.clone(data_type=str) self.assertEqual(cloned_ndmap.data_type, str) def test_idxmapping_apply_key_type(self): data = dict([(0.5, 'a'), (1.5, 'b')]) ndmap = NdIndexableMapping(data, dimensions=[self.dim1]) self.assertEqual(ndmap.keys(), [0, 1]) if __name__ == "__main__": import nose nose.runmodule(argv=[sys.argv[0], "--logging-level", "ERROR"])
assert self.real_output[i] == self.expected_output[i], \ "Real output %r doesn't match to expected %r for example #%s" % (self.real_output[i], self.expected_output[i], i) def test_example(): for example in EXAMPLES: runner = ExampleFileTestSuite(example) # we want to have granular test, one test case per line # nose show each test as "executable, arg1, arg2", that's # why we want pass example name again, even test runner already knows it for i in runner.test_cases(): yield runner.run_test, example, i def assert_python_version(current_version): exec_version = subprocess.check_output( ['python', '-c', 'import sys; print(sys.version_info)'], stderr=subprocess.STDOUT).strip() assert current_version == exec_version.decode('utf-8') def test_python_version(): # check that `python something.py` will run the same version interepreter as it is running import sys current_version = str(sys.version_info) # do a yield to show in the test output the python version yield assert_python_version, current_version if __name__ == '__main__': import nose, sys if not nose.runmodule(): sys.exit(1)
called_save.append(True) def write_cells(self, *args, **kwargs): called_write_cells.append(True) def check_called(func): func() self.assertTrue(len(called_save) >= 1) self.assertTrue(len(called_write_cells) >= 1) del called_save[:] del called_write_cells[:] register_writer(DummyClass) writer = ExcelWriter('something.test') tm.assert_isinstance(writer, DummyClass) df = tm.makeCustomDataframe(1, 1) panel = tm.makePanel() func = lambda: df.to_excel('something.test') check_called(func) check_called(lambda: panel.to_excel('something.test')) val = get_option('io.excel.xlsx.writer') set_option('io.excel.xlsx.writer', 'dummy') check_called(lambda: df.to_excel('something.xlsx')) check_called(lambda: df.to_excel('something.xls', engine='dummy')) set_option('io.excel.xlsx.writer', val) if __name__ == '__main__': nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], exit=False)
F = f.integ() exact = F(b) - F(a) assert_allclose(gk_quad(f,a,b, n=n)[0], exact, rtol=1e-14,atol=0) class test_shanks(unittest.TestCase): """tests for shanks""" def test_pi(self): """4 * sum((-1)**k * (2 * k+1)**(-1))""" nn = 10 seq = np.array([4*sum((-1)**n/(2*n+1) for n in range(m)) for m in range(1, nn)]) assert_allclose(shanks(seq, -8), np.pi, atol=1e-6) def test_pi_max_shanks_ind(self): """4 * sum((-1)**k * (2 * k+1)**(-1))""" nn = 10 seq = np.array([4*sum((-1)**n/(2*n+1) for n in range(m)) for m in range(1, nn)]) assert_allclose(shanks(seq, -50), np.pi, atol=1e-8) if __name__ == '__main__': import nose nose.runmodule(argv=['nose', '--verbosity=3', '--with-doctest']) # nose.runmodule(argv=['nose', '--verbosity=3'])
from nose.tools.trivial import ok_ from numpy.testing import assert_allclose import math import numpy as np from geotecha.piecewise.piecewise_linear_1d import PolyLine from geotecha.mathematics.root_finding import find_n_roots from scipy.special import j0 def test_find_n_roots(): """test for find_n_roots""" #find_n_roots(func, args=(), n=1, x0=0.001, dx=0.001, p=1.0, fsolve_kwargs={}): assert_allclose(find_n_roots(math.sin, n=3, x0=0.1, dx=0.1, p=1.01), np.arange(1, 4) * np.pi, atol=1e-5) #bessel roots from http://mathworld.wolfram.com/BesselFunctionZeros.html assert_allclose(find_n_roots(j0, n=3, x0=0.1, dx=0.1, p=1.01), np.array([2.4048, 5.5201, 8.6537]), atol=1e-4) if __name__ == '__main__': import nose nose.runmodule(argv=['nose', '--verbosity=3', '--with-doctest']) # nose.runmodule(argv=['nose', '--verbosity=3'])
np.transpose, obj, axes=1) class TestNoNewAttributesMixin(tm.TestCase): def test_mixin(self): class T(NoNewAttributesMixin): pass t = T() self.assertFalse(hasattr(t, "__frozen")) t.a = "test" self.assertEqual(t.a, "test") t._freeze() # self.assertTrue("__frozen" not in dir(t)) self.assertIs(getattr(t, "__frozen"), True) def f(): t.b = "test" self.assertRaises(AttributeError, f) self.assertFalse(hasattr(t, "b")) if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], # '--with-coverage', '--cover-package=pandas.core'], exit=False)
for name, expected in zip(('HairEyeColor', 'Titanic', 'iris3'), (hec, titanic, iris3)): df = com.load_data(name) table = r[name] names = r['dimnames'](table) try: columns = list(r['names'](names))[::-1] except TypeError: columns = ['X{:d}'.format(i) for i in range(len(names))][::-1] columns.append('value') assert np.array_equal(df.columns, columns) result = df.head() cond = ((result.sort(axis=1) == expected.sort(axis=1))).values assert np.all(cond) def test_factor(self): for name in ('state.division', 'state.region'): vector = r[name] factors = list(r['factor'](vector)) level = list(r['levels'](vector)) factors = [level[index - 1] for index in factors] result = com.load_data(name) assert np.equal(result, factors) if __name__ == '__main__': nose.runmodule( argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], # '--with-coverage', '--cover-package=pandas.core'], exit=False)
def test_endog_only_raise(self): np.testing.assert_raises(Exception, sm_data.handle_data, (self.y, None, 'raise')) def test_endog_only_drop(self): y = self.y y = y.dropna() data = sm_data.handle_data(self.y, None, 'drop') np.testing.assert_array_equal(data.endog, y.values) def test_mv_endog(self): y = self.X y = y.ix[~np.isnan(y.values).any(axis=1)] data = sm_data.handle_data(self.X, None, 'drop') np.testing.assert_array_equal(data.endog, y.values) def test_labels(self): 2, 10, 14 labels = pandas.Index([0, 1, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24]) data = sm_data.handle_data(self.y, self.X, 'drop') np.testing.assert_(data.row_labels.equals(labels)) if __name__ == "__main__": import nose #nose.runmodule(argv=[__file__, '-vvs', '-x', '--pdb', '--pdb-failure'], # exit=False) nose.runmodule(argv=[__file__, '-vvs', '-x'], exit=False)
def test_overlapping_linear(self): assert_allclose(back_calc_drain_spacing_from_eta(0.71017973670799939, 't', mu_overlapping_linear, 0.05, 5, 2, muw=1), [ 1.61711464, 0.84904594, 16.9809188 ], atol=1e-4) def test_n_falls_below_s(self): assert_raises(ValueError, back_calc_drain_spacing_from_eta, 5, 't', mu_constant, 0.05, 5, 2, muw=1) def test_multipe_s(self): assert_raises(ValueError, back_calc_drain_spacing_from_eta, 1, 't', mu_constant, 0.05, [5,6], 2, muw=1) def test_multipe_kap(self): assert_raises(ValueError, back_calc_drain_spacing_from_eta, 1, 't', mu_constant, 0.05, [5,6], 2, muw=1) if __name__ == '__main__': import nose # nose.runmodule(argv=['nose', '--verbosity=3', '--with-doctest']) nose.runmodule(argv=['nose', 'test_smear_zones:test_mu_parabolic.test_s_n_unequal_len', '--verbosity=3', '--with-doctest', '--doctest-options=+ELLIPSIS']) # nose.runmodule(argv=['nosetests', 'test_foxcon:test_foxcon.test__update_Hlayers', '--verbosity=3', '--with-doctest', '--doctest-options=+ELLIPSIS']) # nose.runmodule(argv=['nose', '--verbosity=3']) #test_mu_parabolic
out = pml_hybrid(synthetic_data(), theta=(0., 1.)) assert_equals(out.shape, (4, 5, 5)) assert_equals(np.isnan(out).sum(), 0) def test_pml_quad(): out = pml_quad(synthetic_data(), theta=(0., 1.)) assert_equals(out.shape, (4, 5, 5)) assert_equals(np.isnan(out).sum(), 0) def test_sirt(): out = sirt(synthetic_data(), theta=(0., 1.)) assert_equals(out.shape, (4, 5, 5)) assert_equals(np.isnan(out).sum(), 0) def test_write_center(): dpath = os.path.join('test', 'tmp') write_center(synthetic_data(), [0., 1.], dpath, center=[3, 5, 0.5]) assert_equals(os.path.isfile(os.path.join(dpath, '3.00.tiff')), True) assert_equals(os.path.isfile(os.path.join(dpath, '3.50.tiff')), True) assert_equals(os.path.isfile(os.path.join(dpath, '4.00.tiff')), True) assert_equals(os.path.isfile(os.path.join(dpath, '4.50.tiff')), True) shutil.rmtree(dpath) if __name__ == '__main__': import nose nose.runmodule(exit=False)
pdf_r = np.array([3.941955996757291e-04, 1.568067236862745e-03, 6.136996029432048e-03, 3.183098861837907e-01, 3.167418189469279e-01, 1.269297588738406e-01]) pdf_st = skewt.pdf(x, 1, 10) #args = (df, alpha) = (1, 10)) assert_(np.allclose(pdf_st, pdf_r, rtol=1e-13, atol=1e-25)) #noquote(sprintf("%.15e,", pst(c(-2,-1, -0.5,0,1,2), shape=10, df=1))) cdf_r = np.array([7.893671370544414e-04, 1.575817262600422e-03, 3.128720749105560e-03, 3.172551743055351e-02, 5.015758172626005e-01, 7.056221318361879e-01]) cdf_st = skewt.cdf(x, 1, 10) #args = (df, alpha) = (1, 10) assert_(np.allclose(cdf_st, cdf_r, rtol=1e-13, atol=1e-25)) if __name__ == '__main__': import nose nose.runmodule(argv=['__main__','-vvs','-x','--pdb', '--pdb-failure'], exit=False) print ('Done') ''' >>> skewt.pdf([-2,-1,0,1,2], 10000000, 10) array([ 2.98557345e-90, 3.68850289e-24, 3.98942271e-01, 4.83941426e-01, 1.07981952e-01]) >>> skewt.pdf([-2,-1,0,1,2], np.inf, 10) array([ nan, nan, nan, nan, nan]) '''
A = np.ones((5, 5)) A[1:2, 1:2] = np.nan ax1.imshow(A, interpolation='nearest') A = np.zeros((5, 5), dtype=np.bool) A[1:2, 1:2] = True A = np.ma.masked_array(np.ones((5, 5), dtype=np.uint16), A) ax2.imshow(A, interpolation='nearest') @image_comparison(baseline_images=['imshow_endianess'], remove_text=True, extensions=['png']) def test_imshow_endianess(): x = np.arange(10) X, Y = np.meshgrid(x, x) Z = ((X-5)**2 + (Y-5)**2)**0.5 fig, (ax1, ax2) = plt.subplots(1, 2) kwargs = dict(origin="lower", interpolation='nearest', cmap='viridis') ax1.imshow(Z.astype('<f8'), **kwargs) ax2.imshow(Z.astype('>f8'), **kwargs) if __name__ == '__main__': nose.runmodule(argv=['-s', '--with-doctest'], exit=False)
---------- value: list or tuple The values to use in the tests """ print(self.traj_file) ideal_atoms, _ = value[0] write_traj = Trajectory(self.traj_file.name, mode='w') traj = [] for i in range(3): write_traj.write(ideal_atoms) traj.append(ideal_atoms) self.traj_file.close() assert os.path.exists(self.traj_file.name) print(self.traj_file) read_traj = TrajectoryReader(self.traj_file.name) print(len(traj), len(read_traj)) assert len(traj) == len(read_traj) del traj if __name__ == '__main__': import nose nose.runmodule(argv=['--with-doctest', # '--nocapture', '-v', '-x' ], exit=False)
neigh = neighbors.NearestNeighbors(n_neighbors=n_neighbors, algorithm=algorithm, metric=metric, **kwds) neigh.fit(X) results.append(neigh.kneighbors(test, return_distance=True)) assert_array_almost_equal(results[0][0], results[1][0]) assert_array_almost_equal(results[0][1], results[1][1]) def test_callable_metric(): metric = lambda x1, x2: np.sqrt(np.sum(x1 ** 2 + x2 ** 2)) X = np.random.RandomState(42).rand(20, 2) nbrs1 = neighbors.NearestNeighbors(3, algorithm='auto', metric=metric) nbrs2 = neighbors.NearestNeighbors(3, algorithm='brute', metric=metric) nbrs1.fit(X) nbrs2.fit(X) dist1, ind1 = nbrs1.kneighbors(X) dist2, ind2 = nbrs2.kneighbors(X) assert_array_almost_equal(dist1, dist2) if __name__ == '__main__': import nose nose.runmodule()
res_olsg = OLS(g_inv, exogg).fit() #> NeweyWest(fm, lag = 4, prewhite = FALSE, sandwich = TRUE, verbose=TRUE, adjust=TRUE) #Lag truncation parameter chosen: 4 # (Intercept) ggdp lint cov1_r = [ [1.40643899878678802, -0.3180328707083329709, -0.060621111216488610], [-0.31803287070833292, 0.1097308348999818661, 0.000395311760301478], [-0.06062111121648865, 0.0003953117603014895, 0.087511528912470993] ] #> NeweyWest(fm, lag = 4, prewhite = FALSE, sandwich = TRUE, verbose=TRUE, adjust=FALSE) #Lag truncation parameter chosen: 4 # (Intercept) ggdp lint cov2_r = [ [1.3855512908840137, -0.313309610252268500, -0.059720797683570477], [-0.3133096102522685, 0.108101169035130618, 0.000389440793564339], [-0.0597207976835705, 0.000389440793564336, 0.086211852740503622] ] cov1, se1 = sw.cov_hac_simple(res_olsg, nlags=4, use_correction=True) cov2, se2 = sw.cov_hac_simple(res_olsg, nlags=4, use_correction=False) assert_almost_equal(cov1, cov1_r, decimal=14) assert_almost_equal(cov2, cov2_r, decimal=14) if __name__ == '__main__': import nose nose.runmodule(argv=[__file__, '-vvs', '-x'], exit=False) #test_hac_simple()