def test_versioned_controllers(self): # putting the C back in CRUD controller_prefix = "versioned_controllers" testdata.create_modules( { "foo": [ "import endpoints", "from endpoints.decorators import param, version", "class Bar(endpoints.Controller):", " @param('foo', default=1, type=int)", " @param('bar', type=bool, required=False)", " @version('v1')", " def GET_v1(self): pass", "", " @version('v2')", " def GET_v2(self): pass", "" ], "che": [ "from endpoints import Controller", "from endpoints.decorators import version", "class Baz(Controller):", " @version('v3')", " def GET_v3(self): pass", "" ], }, prefix=controller_prefix) rs = self.create_reflect(controller_prefix) l = list(rs.controllers) self.assertEqual(2, len(l)) for d in l: self.assertEqual(2, len(d.methods)) d = self.find_reflect("/foo/bar", l) self.assertTrue(d) d = self.find_reflect("/che/baz", l) self.assertTrue(d)
def test_decorators(self): testdata.create_modules({ "controller_reflect.foo": os.linesep.join([ "def dec_func(f):", " def wrapped(*args, **kwargs):", " return f(*args, **kwargs)", " return wrapped", "", "class dec_cls(object):", " def __init__(self, func):", " self.func = func", " def __call__(*args, **kwargs):", " return f(*args, **kwargs)", "", "import endpoints", "class Default(endpoints.Controller):", " @dec_func", " def GET(*args, **kwargs): pass", " @dec_cls", " def POST(*args, **kwargs): pass", "" ]) }) r = endpoints.Reflect("controller_reflect") l = r.get_endpoints() self.assertEqual(1, len(l)) self.assertEqual(u'/foo', l[0]['endpoint']) self.assertEqual(['GET', 'POST'], l[0]['options'])
def test_query_ref_2(self): testdata.create_modules({ "qre": "\n".join([ "import prom", "", "class T1(prom.Orm):", " table_name = 'qre_t1'", "" "class T2(prom.Orm):", " table_name = 'qre_t2'", " t1_id=prom.Field(T1, True)", "" "class T3(prom.Orm):", " table_name = 'qre_t3'", "" ]) }) from qre import T1, T2, T3 t1a = T1.create() t1b = T1.create() t2 = T2.create(t1_id=t1a.pk) classpath = "{}.{}".format(T3.__module__, T3.__name__) with self.assertRaises(ValueError): T1.query.ref(classpath, t1a.pk).count() classpath = "{}.{}".format(T2.__module__, T2.__name__) r = T1.query.ref(classpath, t1a.pk).count() self.assertEqual(1, r) r = T1.query.ref(classpath, t1b.pk).count() self.assertEqual(0, r)
def test_multi(self): # if there is an error in one of the tests but another test is found, don't # bubble up the error cwd = testdata.create_dir() testdata.create_modules( { "multi.bar_test": "\n".join( ["from unittest import TestCase", "", "class BarTest(TestCase):", " def test_bar(self): pass"] ), "multi.foo_test": "\n".join( [ "from unittest import TestCase", "", "class FooTest(TestCase):", " def test_foo(self): pass", "", "class CheTest(TestCase):", " def test_che(self): pass", ] ), }, tmpdir=cwd, ) ret_code = tester.run_test("multi.", cwd) self.assertEqual(0, ret_code)
def test_get_endpoints(self): # putting the C back in CRUD tmpdir = testdata.create_dir("reflecttest") testdata.create_modules( { "controller_reflect": os.linesep.join([ "import endpoints", "class Default(endpoints.Controller):", " def GET(*args, **kwargs): pass", "" ]), "controller_reflect.foo": os.linesep.join([ "import endpoints", "class Default(endpoints.Controller):", " def GET(*args, **kwargs): pass", "" ]), "controller_reflect.che": os.linesep.join([ "from endpoints import Controller", "class Baz(Controller):", " def POST(*args, **kwargs): pass", "" ]), "controller_reflect.che.bam": os.linesep.join([ "from endpoints import Controller as Con", "class _Base(Con):", " def GET(*args, **kwargs): pass", "", "class Boo(_Base):", " def DELETE(*args, **kwargs): pass", " def POST(*args, **kwargs): pass", "" "class Bah(_Base):", " '''this is the doc string'''", " def HEAD(*args, **kwargs): pass", "" ]) }, tmpdir=tmpdir ) r = endpoints.Reflect("controller_reflect") l = r.get_endpoints() self.assertEqual(5, len(l)) def get_match(endpoint, l): for d in l: if d['endpoint'] == endpoint: return d d = get_match("/che/bam/bah", l) self.assertEqual(d['options'], ["GET", "HEAD"]) self.assertGreater(len(d['doc']), 0) d = get_match("/", l) self.assertNotEqual(d, {}) d = get_match("/foo", l) self.assertNotEqual(d, {})
def test_relative_import(self): cwd = testdata.create_dir() testdata.create_modules( { "ritests": "from unittest import TestCase", "ritests.foo_test": "\n".join( ["from . import TestCase", "", "class FooTest(TestCase):", " def test_bar(self): pass"] ), }, tmpdir=cwd, ) ret_code = tester.run_test("Foo.bar", cwd)
def test_controllers(self): # putting the C back in CRUD controller_prefix = "controller_reflect_endpoints" testdata.create_modules({ controller_prefix: [ "import endpoints", "class Default(endpoints.Controller):", " def GET(*args, **kwargs): pass", "" ], "{}.foo".format(controller_prefix): [ "import endpoints", "class Default(endpoints.Controller):", " def GET(*args, **kwargs): pass", "" ], "{}.che".format(controller_prefix): [ "from endpoints import Controller", "class Baz(Controller):", " def POST(*args, **kwargs): pass", "" ], "{}.che.bam".format(controller_prefix): [ "from endpoints import Controller as Con", "class _Base(Con):", " def GET(*args, **kwargs): pass", "", "class Boo(_Base):", " def DELETE(*args, **kwargs): pass", " def POST(*args, **kwargs): pass", "" "class Bah(_Base):", " '''this is the doc string'''", " def HEAD(*args, **kwargs): pass", "" ] }) r = self.create_reflect(controller_prefix) l = list(r.controllers) self.assertEqual(5, len(l)) d = self.find_reflect("/che/bam/bah", l) self.assertSetEqual(set(["GET", "HEAD", "OPTIONS"]), set(d.methods.keys())) self.assertGreater(len(d.desc), 0) d = self.find_reflect("/", l) self.assertNotEqual(d, None) d = self.find_reflect("/foo", l) self.assertNotEqual(d, None)
def test_no_tests_found(self): # if there is an error in one of the tests but another test is found, don't # bubble up the error cwd = testdata.create_dir() testdata.create_modules( { "nofound.nofo_test": "\n".join( ["from unittest import TestCase", "", "class NofoTest(TestCase):", " def test_nofo(self): pass"] ) }, tmpdir=cwd, ) ret_code = tester.run_test("nofound_does_not_exist.", cwd) self.assertEqual(1, ret_code)
def test_string_ref(self): modname = testdata.get_module_name() d = testdata.create_modules( { "foo": [ "import prom", "class Foo(prom.Orm):", " interface = None", " bar_id = prom.Field('{}.bar.Bar')".format(modname), "" ], "bar": [ "import prom", "class Bar(prom.Orm):", " interface = None", " foo_id = prom.Field('{}.foo.Foo')".format(modname), "" ], }, modname) Foo = d.module("{}.foo".format(modname)).Foo Bar = d.module("{}.bar".format(modname)).Bar self.assertTrue(isinstance(Foo.schema.fields['bar_id'].schema, Schema)) self.assertTrue( issubclass(Foo.schema.fields['bar_id'].interface_type, long)) self.assertTrue(isinstance(Bar.schema.fields['foo_id'].schema, Schema)) self.assertTrue( issubclass(Bar.schema.fields['foo_id'].interface_type, long))
def test_ref_threading(self): basedir = testdata.create_modules({ "rtfoo.rtbar.tqr1": [ "import prom", "", "class Foo(prom.Orm):", " table_name = 'thrd_qr2_foo'", " one=prom.Field(int, True)", "", ], "rtfoo.rtbar.tqr2": [ "import prom", "from tqr1 import Foo", "", "class Bar(prom.Orm):", " table_name = 'thrd_qr2_bar'", " one=prom.Field(int, True)", " foo_id=prom.Field(Foo, True)", "" ] }) tqr1 = basedir.module("rtfoo.rtbar.tqr1") sys.modules.pop("rtfoo.rtbar.tqr2.Bar", None) #tqr2 = basedir.module("tqr2") def target(): q = tqr1.Foo.query.ref("rtfoo.rtbar.tqr2.Bar") f = tqr1.Foo() q = f.query.ref("rtfoo.rtbar.tqr2.Bar") t1 = Thread(target=target) # if we don't get stuck in a deadlock this test passes t1.start() t1.join()
def test_modules_submodules(self): path = testdata.create_modules({ "foo": [ "import boto3", ], "foo.bar": [ "import os", "import sys", ], "foo.che": [ "from . import bar", ], "foo.bar2.che2": [] }) expected = set(["foo.che", "foo.bar", "foo.bar2", "foo.bar2.che2"]) ps = Packages() p = ps["foo"] sms = set([sm for sm in p.submodules()]) self.assertEqual(expected, sms) sms = set([sm for sm in p.modules()]) self.assertTrue("foo" in sms)
def test_mixed_modules_packages(self): """make sure a package with modules and other packages will resolve correctly""" controller_prefix = "mmp" r = testdata.create_modules({ "": [ "from endpoints import Controller", "class Default(Controller): pass", ], "foo": [ "from endpoints import Controller", "class Default(Controller): pass", ], "foo.bar": [ "from endpoints import Controller", "class Default(Controller): pass", ], "che": [ "from endpoints import Controller", "class Default(Controller): pass", ], }, prefix=controller_prefix) r = ReflectModule(controller_prefix) self.assertEqual(set(['mmp.foo', 'mmp', 'mmp.foo.bar', 'mmp.che']), r.module_names) # make sure just a file will resolve correctly controller_prefix = "mmp2" testdata.create_module(controller_prefix, os.linesep.join([ "from endpoints import Controller", "class Bar(Controller): pass", ])) r = ReflectModule(controller_prefix) self.assertEqual(set(['mmp2']), r.module_names)
def test_create_modules_2(self): prefix = "testdata_cm2" r = testdata.create_modules({ prefix: os.linesep.join([ "class Default(object):", " def GET(*args, **kwargs): pass", "" ]), "{}.default".format(prefix): os.linesep.join([ "class Default(object):", " def GET(*args, **kwargs): pass", "" ]), "{}.foo".format(prefix): os.linesep.join([ "class Default(object):", " def GET(*args, **kwargs): pass", "", "class Bar(object):", " def GET(*args, **kwargs): pass", " def POST(*args, **kwargs): pass", "" ]), "{}.foo.baz".format(prefix): os.linesep.join([ "class Default(object):", " def GET(*args, **kwargs): pass", "", "class Che(object):", " def GET(*args, **kwargs): pass", "" ]), }) module = importlib.import_module(prefix) class_name = getattr(module, "Default") instance = class_name()
def test_modules_1(self): mpath = testdata.create_modules({ "test_modules.foo": [ "class Foo(object): pass", "class Bar(object): pass", "", ], "test_modules.bar": [ "class Che(object): pass", "class Bar(object): pass", "", ], "test_modules.che": [ "class Baz(object): pass", "", ], }) mp = mpath.modpath("test_modules") mps = list(mp.modpaths()) self.assertTrue(3, len(mps)) for modpath in ["test_modules.foo", "test_modules.bar", "test_modules.che"]: self.assertTrue(modpath in mps) klasses = list(mp.classes) self.assertEqual(5, len(klasses))
def test_relative_import(self): basedir = testdata.create_modules({ "relimp.foo.bar": [ "class Bar(object): pass", "", ], "relimp.foo.che": ["class Che(object): pass", ""], "relimp.foo": ["class Foo(object): pass", ""], "relimp": ["class Relimp(object): pass", ""], "relimp.baz": ["class Baz(object): pass", ""] }) with self.assertRaises(ImportError): module, klass = get_objects('...too.far', "relimp.foo.bar") module, klass = get_objects('...baz.Baz', "relimp.foo.bar") self.assertEqual("relimp.baz", module.__name__) self.assertEqual("Baz", klass.__name__) module, klass = get_objects('..che.Che', "relimp.foo.bar") self.assertEqual("relimp.foo.che", module.__name__) self.assertEqual("Che", klass.__name__) module, klass = get_objects('...foo.Foo', "relimp.foo.bar") self.assertEqual("relimp.foo", module.__name__) self.assertEqual("Foo", klass.__name__) module, klass = get_objects('relimp.Relimp', "relimp.foo.bar") self.assertEqual("relimp", module.__name__) self.assertEqual("Relimp", klass.__name__)
def test_double_counting_and_pyc(self): """Make sure packages don't get double counted""" # https://github.com/Jaymon/pyt/issues/18 # https://github.com/Jaymon/pyt/issues/19 basedir = testdata.create_modules( { "dc_test": "", "dc_test.bar_test": [ "from unittest import TestCase", "class BarTest(TestCase):", " def test_baz(self): pass", ], "dc_test.che_test": [ "from unittest import TestCase", "class CheTest(TestCase):", " def test_baz(self): pass", ], } ) s = Client(basedir) r = s.run("dc_test --debug") self.assertTrue("Found 2 total tests" in r) # running it again will test for the pyc problem r = s.run("dc_test --debug") self.assertFalse("No module named pyc" in r) r = s.run("--all --debug") self.assertTrue("Found 2 total tests" in r) r = s.run("--all --debug") self.assertFalse("No module named pyc" in r)
def test_no_match(self): """make sure a controller module that imports a class with the same as one of the query args doesen't get picked up as the controller class""" controller_prefix = "nomodcontroller" contents = { "{}.nomod".format(controller_prefix): [ "class Nomodbar(object): pass", "" ], controller_prefix: [ "from endpoints import Controller", "from .nomod import Nomodbar", "class Default(Controller):", " def GET(): pass", "" ] } m = testdata.create_modules(contents) path = '/nomodbar' # same name as one of the non controller classes r = Router([controller_prefix]) info = r.find(*self.get_http_instances(path)) self.assertEqual('Default', info['class_name']) self.assertEqual('nomodcontroller', info['module_name']) self.assertEqual('nomodbar', info['method_args'][0])
def test_no_match(self): """make sure a controller module that imports a class with the same as one of the query args doesen't get picked up as the controller class""" controller_prefix = "nomodcontroller" r = testdata.create_modules({ "nomod": os.linesep.join([ "class Nomodbar(object): pass", "" ]), controller_prefix: os.linesep.join([ "from endpoints import Controller", "from nomod import Nomodbar", "class Default(Controller):", " def GET(): pass", "" ]) }) c = endpoints.Call(controller_prefix) r = endpoints.Request() r.method = 'GET' r.path = '/nomodbar' # same name as one of the non controller classes c.request = r info = c.get_controller_info() self.assertEqual('Default', info['class_name']) self.assertEqual('nomodcontroller', info['module_name']) self.assertEqual('nomodbar', info['args'][0])
def test_query_ref(self): testdata.create_modules({ "qr2": "\n".join([ "import prom", "", "class Foo(prom.Orm):", " table_name = 'qr2_foo'", " foo=prom.Field(int, True)", " bar=prom.Field(str, True)", "" "class Bar(prom.Orm):", " table_name = 'qr2_bar'", " foo=prom.Field(int, True)", " bar=prom.Field(str, True)", " che=prom.Field(Foo, True)", "" ]) }) from qr2 import Foo as t1, Bar as t2 ti1 = t1.create(foo=11, bar='11') ti12 = t1.create(foo=12, bar='12') ti2 = t2.create(foo=21, bar='21', che=ti1.pk) ti22 = t2.create(foo=22, bar='22', che=ti12.pk) orm_classpath = "{}.{}".format(t2.__module__, t2.__name__) l = list(ti1.query.ref(orm_classpath, ti12.pk).select_foo().values()) self.assertEqual(22, l[0]) self.assertEqual(1, len(l)) l = list(ti1.query.ref(orm_classpath, ti1.pk).select_foo().all().values()) self.assertEqual(21, l[0]) self.assertEqual(1, len(l)) l = list(ti1.query.ref(orm_classpath, ti1.pk).select_foo().get().values()) self.assertEqual(21, l[0]) self.assertEqual(1, len(l)) l = list(ti1.query.ref(orm_classpath, ti1.pk).select_foo().values()) self.assertEqual(21, l[0]) self.assertEqual(1, len(l)) l = list(ti1.query.ref(orm_classpath).select_foo().all().values()) self.assertEqual(2, len(l))
def test_query_ref(self): testdata.create_modules({ "qr2": "\n".join([ "import prom", "", "class Foo(prom.Orm):", " table_name = 'qr2_foo'", " foo=prom.Field(int, True)", " bar=prom.Field(str, True)", "" "class Bar(prom.Orm):", " table_name = 'qr2_bar'", " foo=prom.Field(int, True)", " bar=prom.Field(str, True)", " che=prom.Field(Foo, True)", "" ]) }) from qr2 import Foo as t1, Bar as t2 ti1 = t1.create(foo=11, bar='11') ti12 = t1.create(foo=12, bar='12') ti2 = t2.create(foo=21, bar='21', che=ti1.pk) ti22 = t2.create(foo=22, bar='22', che=ti12.pk) orm_classpath = "{}.{}".format(t2.__module__, t2.__name__) l = list(ti1.query.ref(orm_classpath, ti12.pk).select_foo().values()) self.assertEqual(22, l[0]) self.assertEqual(1, len(l)) l = list( ti1.query.ref(orm_classpath, ti1.pk).select_foo().all().values()) self.assertEqual(21, l[0]) self.assertEqual(1, len(l)) l = list( ti1.query.ref(orm_classpath, ti1.pk).select_foo().get().values()) self.assertEqual(21, l[0]) self.assertEqual(1, len(l)) l = list(ti1.query.ref(orm_classpath, ti1.pk).select_foo().values()) self.assertEqual(21, l[0]) self.assertEqual(1, len(l)) l = list(ti1.query.ref(orm_classpath).select_foo().all().values()) self.assertEqual(2, len(l))
def test_parse_error(self): cwd = testdata.create_dir() testdata.create_modules( { "tests_parse_error": "from unittest import TestCase", "tests_parse_error.pefoo_test": "\n".join( [ "from . import TestCase", "", "class PEFooTest(TestCase):", " def test_bar(self):", ' foo = "this is a parse error', ] ), }, tmpdir=cwd, ) with self.assertRaises(SyntaxError): ret_code = tester.run_test("PEFoo.bar", cwd)
def test_string_ref(self): testdata.create_modules({ "stringref.foo": "\n".join([ "import prom", "class Foo(prom.Orm):", " interface = None", " bar_id = prom.Field('stringref.bar.Bar')", "" ]), "stringref.bar": "\n".join([ "import prom", "class Bar(prom.Orm):", " interface = None", " foo_id = prom.Field('stringref.foo.Foo')", "" ]) }) from stringref.foo import Foo from stringref.bar import Bar self.assertTrue(isinstance(Foo.schema.fields['bar_id'].schema, Schema)) self.assertTrue(issubclass(Foo.schema.fields['bar_id'].type, long)) self.assertTrue(isinstance(Bar.schema.fields['foo_id'].schema, Schema)) self.assertTrue(issubclass(Bar.schema.fields['foo_id'].type, long))
def test_controllers(self): controller_prefix = "get_controllers" d = { controller_prefix: [ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "" ], "{}.default".format(controller_prefix): [ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "" ], "{}.foo".format(controller_prefix): [ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "", "class Bar(Controller):", " def GET(*args, **kwargs): pass", " def POST(*args, **kwargs): pass", "" ], "{}.foo.baz".format(controller_prefix): [ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "", "class Che(Controller):", " def GET(*args, **kwargs): pass", "" ], "{}.foo.boom".format(controller_prefix): [ "from endpoints import Controller", "", "class Bang(Controller):", " def GET(*args, **kwargs): pass", "" ], } r = testdata.create_modules(d) s = set(d.keys()) r = ReflectModule(controller_prefix) controllers = r.module_names self.assertEqual(s, controllers) # just making sure it always returns the same list controllers = r.module_names self.assertEqual(s, controllers)
def test_no_match(self): """make sure a controller module that imports a class with the same as one of the query args doesen't get picked up as the controller class""" controller_prefix = "nomodcontroller" contents = { "{}.nomod".format(controller_prefix): ["class Nomodbar(object): pass", ""], controller_prefix: [ "from endpoints import Controller", "from nomod import Nomodbar", "class Default(Controller):", " def GET(): pass", "" ] } testdata.create_modules(contents) path = '/nomodbar' # same name as one of the non controller classes r = Router(controller_prefix) info = r.find(*self.get_http_instances(path)) self.assertEqual('Default', info['class_name']) self.assertEqual('nomodcontroller', info['module_name']) self.assertEqual('nomodbar', info['method_args'][0])
def __init__(self, *body, **kwargs): if "cwd" in kwargs: self.cwd = kwargs["cwd"] else: self.cwd = testdata.create_dir() name = kwargs.get('name', None) if name is not None: self.name = name else: self.name = "prefix{}.pmod{}_test".format( testdata.get_ascii(5).lower(), testdata.get_ascii(5).lower() ) self.module_name = "" self.prefix = "" self.name_prefix = "" if name: bits = self.name.rsplit('.', 1) self.module_name = bits[1] if len(bits) == 2 else bits[0] self.prefix = bits[0] if len(bits) == 2 else '' self.name_prefix = bits[1][:4] if len(bits) == 2 else bits[0][:4] if len(body) == 1: body = body[0] self.body = body if isinstance(self.body, dict): for k in self.body: self.body[k] = self._prepare_body(self.body[k]) self.modules = testdata.create_modules( self.body, self.cwd, prefix=self.name, ) self.path = self.modules.path else: if kwargs.get("package", False): self.module = testdata.create_package( self.name, self._prepare_body(self.body), self.cwd ) else: self.module = testdata.create_module( self.name, self._prepare_body(self.body), self.cwd ) self.path = self.module.path
def test_ignore_non_test_modules(self): """make sure similar named non-test modules are ignored""" cwd = testdata.create_dir() testdata.create_modules( { "tintm.tint_test": "\n".join( [ "from unittest import TestCase", "", "class FooTest(TestCase):", " def test_foo(self):", " pass", ] ), "tintm.tint": "", }, tmpdir=cwd, ) s = Client(cwd) r = s.run("tint --debug") self.assertEqual(1, r.count("Found module test"))
def test_versioned_controllers(self): # putting the C back in CRUD controller_prefix = "versioned_controllers" testdata.create_modules({ "foo": [ "import endpoints", "from endpoints.decorators import param, version", "class Bar(endpoints.Controller):", " @param('foo', default=1, type=int)", " @param('bar', type=bool, required=False)", " @version('v1')", " def GET_v1(self): pass", "", " @version('v2')", " def GET_v2(self): pass", "" ], "che": [ "from endpoints import Controller", "from endpoints.decorators import version", "class Baz(Controller):", " @version('v3')", " def GET_v3(self): pass", "" ], }, prefix=controller_prefix) rs = self.create_reflect(controller_prefix) l = list(rs.controllers) self.assertEqual(2, len(l)) for d in l: self.assertEqual(2, len(d.methods)) d = self.find_reflect("/foo/bar", l) self.assertTrue(d) d = self.find_reflect("/che/baz", l) self.assertTrue(d)
def test_get_endpoints(self): # putting the C back in CRUD tmpdir = testdata.create_dir("versionreflecttest") testdata.create_modules( { "controller_vreflect.v1.foo": os.linesep.join([ "import endpoints", "class Bar(endpoints.Controller):", " def GET(*args, **kwargs): pass", "" ]), "controller_vreflect.v2.che": os.linesep.join([ "from endpoints import Controller", "class Baz(Controller):", " def GET(*args, **kwargs): pass", "" ]), }, tmpdir=tmpdir ) r = endpoints.VersionReflect("controller_vreflect", 'application/json') l = r.get_endpoints() self.assertEqual(2, len(l)) for d in l: self.assertTrue('headers' in d) self.assertTrue("version" in d) def get_match(endpoint, l): ret = {} for d in l: if d['endpoint'] == endpoint: ret = d return ret d = get_match("/foo/bar", l) self.assertNotEqual({}, d)
def test_cli_errors(self): # if there is an error in one of the tests but another test is found, don't # bubble up the error cwd = testdata.create_dir() testdata.create_modules( { "cli_2": "from unittest import TestCase", "cli_2.clibar_test": "\n".join(["from . import TestCase", "", "raise ValueError('foo')"]), "cli_2.clifoo_test": "\n".join( ["from . import TestCase", "", "class CliFooTest(TestCase):", " def test_bar(self): pass"] ), }, tmpdir=cwd, ) ret_code = tester.run_test("cli_2.", cwd) self.assertEqual(0, ret_code) # if there is an error and no other test is found, bubble up the error m = TestModule("from unittest import TestCase", "", "raise ValueError('foo')") with self.assertRaises(ValueError): ret_code = tester.run_test(m.name_prefix, m.cwd)
def test_find_modules(self): prefix = "findmodules" path = testdata.create_modules( { "foo": ["class Foo(object): pass"], "foo.bar": ["class Bar1(object): pass", "class Bar2(object): pass"], "che": ["class Che(object): pass"], }, prefix=prefix) r = ReflectPath(path) ms = list(r.find_modules(lambda rm: rm.module_name.endswith("foo"))) self.assertEqual(1, len(ms)) self.assertEqual("{}.foo".format(prefix), ms[0].module_name)
def __init__(self, controller_prefix, contents): super(Server, self).__init__(controller_prefix=controller_prefix, ) if isinstance(contents, dict): d = {} for k, v in contents.items(): if k: d[".".join([controller_prefix, k])] = v else: d[controller_prefix] = v self.controllers = testdata.create_modules(d) else: self.controller = testdata.create_module(controller_prefix, contents=contents)
def test_create_modules(self): ts = [ OrderedDict([ ("foo2.bar", u"class Che(object): pass"), ("foo2.bar.baz", u"class Che(object): pass"), ]) ] tmpdir = testdata.create_dir(u"") for t in ts: testdata.create_modules(t, tmpdir=tmpdir) for k in t.keys(): module = importlib.import_module(k) class_name = getattr(module, "Che") instance = class_name() self.assertEqual(k, instance.__module__) for v in ['foo2/bar']: v = os.path.join(tmpdir, v) self.assertTrue(os.path.isdir(v)) for v in ['foo2/__init__.py', 'foo2/bar/__init__.py', 'foo2/bar/baz.py']: v = os.path.join(tmpdir, v) self.assertTrue(os.path.isfile(v))
def __init__(self, controller_prefix, contents): super(Server, self).__init__( controller_prefixes=[controller_prefix] ) if isinstance(contents, dict): d = {} for k, v in contents.items(): if k: d[".".join([controller_prefix, k])] = v else: d[controller_prefix] = v self.controllers = testdata.create_modules(d) else: self.controller = testdata.create_module(controller_prefix, contents=contents)
def test_get_controller_info_default(self): """I introduced a bug on 1-12-14 that caused default controllers to fail to be found, this makes sure that bug is squashed""" controller_prefix = "controller_info_default" r = testdata.create_modules({ controller_prefix: os.linesep.join([ "from endpoints import Controller", "class Default(Controller):", " def GET(): pass", "" ]) }) r = Router([controller_prefix]) info = r.find(*self.get_http_instances("/")) self.assertEqual('Default', info['class_name']) self.assertTrue(issubclass(info['class'], Controller))
def test_issue_26(self): path = testdata.create_modules({ "foo_test": [], "foo_test.bar": [], "foo_test.bar.che_test": [ "from unittest import TestCase", "", "class Issue26TestCase(TestCase):", " def test_boo(self):", " pass", ] }) pf = PathFinder( basedir=path, module_name="che", prefix="foo/bar", filepath="", ) self.assertEqual(1, len(list(pf.paths()))) pf = PathFinder( basedir=path, module_name="foo", prefix="", filepath="", ) self.assertEqual(2, len(list(pf.paths()))) pf = PathFinder( basedir=path, method_name="boo", class_name="Issue26", module_name="bar", prefix="foo_test", filepath="", ) ti = PathGuesser("foo_test.bar.Issue26.boo", path) self.assertEqual("test_boo", list(pf.method_names())[0][1]) pf = PathFinder( basedir=path, module_name="bar", prefix="foo", filepath="", ) self.assertEqual(1, len(list(pf.paths())))
def test_modules(self): prefix = "reflectmodules" path = testdata.create_modules( { "foo": ["class Foo(object): pass"], "foo.bar": ["class Bar1(object): pass", "class Bar2(object): pass"], "che": ["class Che(object): pass"], }, prefix=prefix) r = ReflectPath(path) s = set([ prefix, "{}.foo".format(prefix), "{}.foo.bar".format(prefix), "{}.che".format(prefix) ]) self.assertEqual(s, r.module_names)
def test_local_package(self): path = testdata.create_modules({ "foo": [ "import boto3", ], "foo.bar": [ "import os", "import sys", ], "foo.che": [ "from . import bar", ], "foo.bar2.che2": [] }) d = Dependencies("foo") self.assertLess(0, len(d))
def __init__(self, *body, **kwargs): if "cwd" in kwargs: self.cwd = kwargs["cwd"] else: self.cwd = testdata.create_dir() name = kwargs.get('name', None) if name is not None: self.name = name else: self.name = "prefix{}.pmod{}_test".format( testdata.get_ascii(5).lower(), testdata.get_ascii(5).lower()) self.module_name = "" self.prefix = "" self.name_prefix = "" if self.name: bits = self.name.rsplit('.', 1) self.module_name = bits[1] if len(bits) == 2 else bits[0] self.prefix = bits[0] if len(bits) == 2 else '' self.name_prefix = bits[1][:4] if len(bits) == 2 else bits[0][:4] if len(body) == 1: body = body[0] self.body = body if isinstance(self.body, dict): for k in self.body: self.body[k] = self._prepare_body(self.body[k]) self.modules = testdata.create_modules( self.body, self.cwd, prefix=self.name, ) self.path = self.modules.path else: if kwargs.get("package", False): self.module = testdata.create_package( self.name, self._prepare_body(self.body), self.cwd) else: self.module = testdata.create_module( self.name, self._prepare_body(self.body), self.cwd) self.path = self.module.path
def create_modules(controller_prefix): d = { controller_prefix: os.linesep.join([ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "" ]), "{}.default".format(controller_prefix): os.linesep.join([ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "" ]), "{}.foo".format(controller_prefix): os.linesep.join([ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "", "class Bar(Controller):", " def GET(*args, **kwargs): pass", " def POST(*args, **kwargs): pass", "" ]), "{}.foo.baz".format(controller_prefix): os.linesep.join([ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "", "class Che(Controller):", " def GET(*args, **kwargs): pass", "" ]), "{}.foo.boom".format(controller_prefix): os.linesep.join([ "from endpoints import Controller", "", "class Bang(Controller):", " def GET(*args, **kwargs): pass", "" ]), } r = testdata.create_modules(d) s = set(d.keys()) return s
def test_multiple_controller_prefixes_1(self): r = testdata.create_modules({ "foo": os.linesep.join([ "from endpoints import Controller", "class Default(Controller): pass", ]), "bar": os.linesep.join([ "from endpoints import Controller", "class User(Controller): pass", ]), }) r = Router(["foo", "bar"]) t = r.find(*self.get_http_instances("/user")) self.assertTrue("bar", t["module_name"]) t = r.find(*self.get_http_instances("/che")) self.assertTrue("foo", t["module_name"])
def test_create_modules_3(self): prefix = "testdata_cm3" r = testdata.create_modules({ "{}.foo.bar".format(prefix): [ "class Bar(object): pass", ], "{}.foo.bar.che.baz".format(prefix): [ "class Baz(object): pass", "" ], }) self.assertEqual(5, len(list(r.modules()))) m = r.module("{}.foo.bar.che.baz".format(prefix)) c = m.Baz() # if this doesn't raise error, it worked mp = r.modpath("{}.foo".format(prefix)) self.assertTrue(mp.is_package())
def test_requires(self): path = testdata.create_modules({ "foo": [ "import boto3", ], "foo.bar": [ "import os", "import sys", ], "foo.che": [ "from . import bar", ], "foo.bar2.che2": ["from .. import bar"] }) ps = Packages() p = ps["foo"] expected = set(["boto3", "sys", "os"]) self.assertEqual(expected, p.requires())
def test_import_error(self): controller_prefix = "importerrorcontroller" r = testdata.create_modules({ controller_prefix: os.linesep.join([ "from endpoints import Controller", "from does_not_exist import FairyDust", "class Default(Controller):", " def GET(): pass", "" ]) }) c = endpoints.Call(controller_prefix) r = endpoints.Request() r.method = 'GET' r.path = '/' c.request = r with self.assertRaises(endpoints.CallError): info = c.get_callback_info()
def test_mixed_modules_packages(self): # make sure a package with modules and other packages will resolve correctly controller_prefix = "mmp" r = testdata.create_modules({ controller_prefix: os.linesep.join([ "from endpoints import Controller", "class Default(Controller): pass", ]), "{}.foo".format(controller_prefix): os.linesep.join([ "from endpoints import Controller", "class Default(Controller): pass", ]), "{}.foo.bar".format(controller_prefix): os.linesep.join([ "from endpoints import Controller", "class Default(Controller): pass", ]), "{}.che".format(controller_prefix): os.linesep.join([ "from endpoints import Controller", "class Default(Controller): pass", ]), }) r = Router(controller_prefix) self.assertEqual(set(['mmp.foo', 'mmp', 'mmp.foo.bar', 'mmp.che']), r.module_names) # make sure just a file will resolve correctly controller_prefix = "mmp2" testdata.create_module( controller_prefix, os.linesep.join([ "from endpoints import Controller", "class Bar(Controller): pass", ])) r = Router(controller_prefix) self.assertEqual(set(['mmp2']), r.module_names)
def test_mixed_modules_packages(self): """make sure a package with modules and other packages will resolve correctly""" controller_prefix = "mmp" r = testdata.create_modules( { "": [ "from endpoints import Controller", "class Default(Controller): pass", ], "foo": [ "from endpoints import Controller", "class Default(Controller): pass", ], "foo.bar": [ "from endpoints import Controller", "class Default(Controller): pass", ], "che": [ "from endpoints import Controller", "class Default(Controller): pass", ], }, prefix=controller_prefix) r = ReflectModule(controller_prefix) self.assertEqual(set(['mmp.foo', 'mmp', 'mmp.foo.bar', 'mmp.che']), r.module_names) # make sure just a file will resolve correctly controller_prefix = "mmp2" testdata.create_module( controller_prefix, os.linesep.join([ "from endpoints import Controller", "class Bar(Controller): pass", ])) r = ReflectModule(controller_prefix) self.assertEqual(set(['mmp2']), r.module_names)
def test_get_controller_info(self): controller_prefix = "controller_info_advanced" r = testdata.create_modules({ controller_prefix: [ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "" ], "{}.default".format(controller_prefix): [ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "" ], "{}.foo".format(controller_prefix): [ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "", "class Bar(Controller):", " def GET(*args, **kwargs): pass", " def POST(*args, **kwargs): pass", "" ], "{}.foo.baz".format(controller_prefix): [ "from endpoints import Controller", "class Default(Controller):", " def GET(*args, **kwargs): pass", "", "class Che(Controller):", " def GET(*args, **kwargs): pass", "" ], "{}.foo.boom".format(controller_prefix): [ "from endpoints import Controller", "", "class Bang(Controller):", " def GET(*args, **kwargs): pass", "" ], }) ts = [ { 'in': dict(method="GET", path="/foo/bar/happy/sad"), 'out': { 'module_name': "controller_info_advanced.foo", 'class_name': 'Bar', 'method_args': ['happy', 'sad'], #'method_name': "GET", } }, { 'in': dict(method="GET", path="/"), 'out': { 'module_name': "controller_info_advanced", 'class_name': 'Default', 'method_args': [], #'method_name': "GET", } }, { 'in': dict(method="GET", path="/happy"), 'out': { 'module_name': "controller_info_advanced", 'class_name': 'Default', 'method_args': ["happy"], #'method_name': "GET", } }, { 'in': dict(method="GET", path="/foo/baz"), 'out': { 'module_name': "controller_info_advanced.foo.baz", 'class_name': 'Default', 'method_args': [], #'method_name': "GET", } }, { 'in': dict(method="GET", path="/foo/baz/che"), 'out': { 'module_name': "controller_info_advanced.foo.baz", 'class_name': 'Che', 'method_args': [], #'method_name': "GET", } }, { 'in': dict(method="GET", path="/foo/baz/happy"), 'out': { 'module_name': "controller_info_advanced.foo.baz", 'class_name': 'Default', 'method_args': ["happy"], #'method_name': "GET", } }, { 'in': dict(method="GET", path="/foo/happy"), 'out': { 'module_name': "controller_info_advanced.foo", 'class_name': 'Default', 'method_args': ["happy"], #'method_name': "GET", } }, ] for t in ts: req, res = self.get_http_instances(**t['in']) # r = Request() # for key, val in t['in'].items(): # setattr(r, key, val) r = Router([controller_prefix]) d = r.find(req, res) for key, val in t['out'].items(): self.assertEqual(val, d[key])