def test_method_docblock_bad_decorator(self): tmpdir = testdata.create_dir("reflectdoc2") controller_prefix = "mdoc2" testdata.create_module(controller_prefix, [ "import endpoints", "", "def bad_dec(func):", " def wrapper(*args, **kwargs):", " return func(*args, **kwargs)", " return wrapper", "", "class Foo(endpoints.Controller):", " '''controller docblock'''", " @bad_dec", " def GET(*args, **kwargs):", " '''method docblock'''", " pass", "", " def POST(*args, **kwargs):", " '''should not return this docblock'''", " pass", "", ]) rs = self.create_reflect(controller_prefix) for endpoint in rs: desc = endpoint.methods['GET'][0].desc self.assertEqual("method docblock", desc)
def test_routing(self): """there was a bug that caused errors raised after the yield to return another iteration of a body instead of raising them""" controller_prefix = "routing1" contents = [ "from endpoints import Controller", "class Default(Controller):", " def GET(self): pass", "", "class Foo(Controller):", " def GET(self): pass", "", "class Bar(Controller):", " def GET(self): pass", ] testdata.create_module(controller_prefix, contents=contents) r = Router([controller_prefix]) info = r.find(*self.get_http_instances()) self.assertEqual(info['module_name'], controller_prefix) self.assertEqual(info['class_name'], "Default") r = Router([controller_prefix]) info = r.find(*self.get_http_instances("/foo/che/baz")) self.assertEqual(2, len(info['method_args'])) self.assertEqual(info['class_name'], "Foo")
def test_issue_24(self): """Turns out I can't fix this issue, so this test is kind of useless""" # trying to setup the environment according to: https://github.com/Jaymon/pyt/issues/24 raise self.skipTest("won't fix") basedir = testdata.create_dir() other_basedir = testdata.create_dir("other/directory", basedir) other_modpath = testdata.create_module("i24tests.model24_test", [ "from unittest import TestCase", "", "class Issue24TestCase(TestCase):", " def test_boo(self):", " pass", ], other_basedir) modpath = testdata.create_module("i24tests.model24_test", [ "from unittest import TestCase", "", "class Issue24TestCase(TestCase):", " def test_boo(self):", " pass", ], basedir) #pout.v(basedir, other_modpath.path, modpath.path) pf = PathFinder(basedir=basedir, module_name="model24", prefix="i24tests", class_name="Issue24", method_name="boo") r = list(pf.method_names()) self.assertEqual(2, len(r)) self.assertNotEqual(r[0], r[1])
def test_patch_class_self(self): """a class that creates itself should create a copy of the patched class""" contents = os.linesep.join([ "class PatchFactory(object):", " def clone(self): return type(self)()", " def bar(self): return 55", "" ]) testdata.create_module("pathclassmod", contents=contents) from pathclassmod import PatchFactory def mock_bar(self): return 33 MonkeyFactory = testdata.patch_class( PatchFactory, bar=mock_bar ) f = PatchFactory() fm = MonkeyFactory() self.assertEqual(55, f.bar()) self.assertEqual(55, f.clone().bar()) self.assertEqual(33, fm.bar()) self.assertEqual(33, fm.clone().bar())
def test_handle_callstop(self): contents = os.linesep.join([ "from endpoints import Controller, CallStop", "class Testcallstop(Controller):", " def GET(*args, **kwargs):", " raise CallStop(205, None)", "class Testcallstop2(Controller):", " def GET(*args, **kwargs):", " raise CallStop(200, 'this is the body')" ]) testdata.create_module("controllerhcs.handlecallstop", contents=contents) r = endpoints.Request() r.path = u"/handlecallstop/testcallstop" r.path_args = [u'handlecallstop', u'testcallstop'] r.query_kwargs = {} r.method = u"GET" c = endpoints.Call("controllerhcs") c.request = r res = c.handle() self.assertEqual('', res.body) self.assertEqual(None, res._body) self.assertEqual(205, res.code) r.path = u"/handlecallstop/testcallstop2" r.path_args = [u'handlecallstop', u'testcallstop2'] res = c.handle() self.assertEqual('"this is the body"', res.body) self.assertEqual(200, res.code)
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_patch(self): @classmethod def mock_bam(*args, **kwargs): return 22 def mock_boom(): return 2 contents = os.linesep.join([ "def boom():", " return 1", "", "class FooPatch(object):", " @classmethod", " def bam(cls): return boom()", "" ]) testdata.create_module("patch.foo", contents=contents) from patch.foo import FooPatch self.assertEqual(1, FooPatch.bam()) FP = testdata.patch(FooPatch, bam=mock_bam) self.assertEqual(22, FP.bam()) from patch import foo self.assertEqual(1, foo.FooPatch.bam()) foo = testdata.patch(foo, boom=mock_boom) self.assertEqual(2, foo.FooPatch.bam()) foo = testdata.patch('patch.foo', boom=mock_boom) self.assertEqual(2, foo.FooPatch.bam())
def test_routing_module(self): controller_prefix = "callback_info" contents = [ "from endpoints import Controller", "class Bar(Controller):", " def GET(*args, **kwargs): pass" ] testdata.create_module("{}.foo".format(controller_prefix), contents=contents) r = Router(controller_prefix) self.assertTrue(controller_prefix in r.module_names) self.assertEqual(2, len(r.module_names))
def test_routing_module(self): controller_prefix = "routing_module" contents = [ "from endpoints import Controller", "class Bar(Controller):", " def GET(*args, **kwargs): pass" ] testdata.create_module("{}.foo".format(controller_prefix), contents=contents) r = ReflectModule(controller_prefix) self.assertTrue(controller_prefix in r.module_names) self.assertEqual(2, len(r.module_names))
def test_ref(self): testdata.create_module( "ref", "\n".join([ "import prom", "class Foo(prom.Orm):", " che = prom.Field(str)", "", "class Bar(prom.Orm):", " foo_id = prom.Field(Foo)", "" ])) from ref import Foo, Bar self.assertTrue(isinstance(Bar.schema.fields['foo_id'].schema, Schema)) self.assertTrue(issubclass(Bar.schema.fields['foo_id'].type, long))
def test_property_autodiscover(self): testdata.create_module("fooq", "\n".join([ "import prom", "", "class FooQuery(prom.Query):", " pass", "", "class Foo(prom.Orm):", " schema = prom.Schema('foo')", " query_class = FooQuery", "", "class BarQuery(prom.Query):", " pass", "", "class Bar(Foo):", " schema = prom.Schema('bar')", " query_class = BarQuery", " pass", "", "class CheQuery(prom.Query):", " pass", ])) import fooq # first try with the instance calling first f = fooq.Foo() self.assertEqual(f.query_class, fooq.Foo.query_class) f = fooq.Foo() self.assertEqual(f.query.__class__.__name__, fooq.Foo.query.__class__.__name__) f = fooq.Foo() self.assertEqual(f.interface, fooq.Foo.interface) # now try with the class calling first b = fooq.Bar() self.assertEqual(fooq.Bar.query_class, b.query_class) b = fooq.Bar() self.assertEqual(fooq.Bar.query.__class__.__name__, b.query.__class__.__name__) b = fooq.Bar() self.assertEqual(fooq.Bar.interface, b.interface) # now make sure we can manipulate it fooq.Foo.query_class = fooq.CheQuery f = fooq.Foo() self.assertEqual(fooq.CheQuery, f.query_class) self.assertEqual(fooq.CheQuery, fooq.Foo.query_class) self.assertEqual(fooq.CheQuery, f.query.__class__) self.assertEqual(fooq.CheQuery, fooq.Foo.query.__class__)
def test_create_module(self): ts = [ ( "foo.bar", "Che", u"class Che(object): pass" ) ] for t in ts: testdata.create_module(t[0], contents=t[2]) module = importlib.import_module(t[0]) class_name = getattr(module, t[1]) instance = class_name()
def test__find_prefix_paths(self): modpath = testdata.create_module("find.prefix.paths.whew_test") pf = PathFinder(basedir=modpath.basedir) r = list(pf._find_prefix_paths(pf.basedir, "find.paths")) self.assertEqual(1, len(r)) basedir = testdata.create_dir() other_basedir = testdata.create_dir("other/directory", basedir) other_modpath = testdata.create_module("tests.fpp_test", [], other_basedir) modpath = testdata.create_module("tests.fpp_test", [], basedir) pf = PathFinder(basedir=basedir) r = list(pf._find_prefix_paths(basedir, "tests")) self.assertEqual(2, len(r))
def test_delete_table_ref(self): path = testdata.create_module("dtref", [ "import prom", "", "class Foo(prom.Orm):", " table_name = 'dtref_foo'", "", "class Bar(prom.Orm):", " table_name = 'dtref_bar'", " foo_id=prom.Field(Foo, True)", " foo2_id=prom.Field(Foo, True)", "" ]) from dtref import Foo, Bar Foo.install() Bar.install() self.assertTrue(Foo.interface.has_table("dtref_foo")) Foo.interface.delete_table("dtref_foo") self.assertFalse(Foo.interface.has_table("dtref_foo")) Bar.interface.close() self.assertFalse(Bar.interface.is_connected()) self.assertTrue(Bar.interface.has_table("dtref_bar")) Bar.interface.delete_tables(disable_protection=True) self.assertFalse(Bar.interface.has_table("dtref_bar"))
def test_glob(self): modpath = testdata.create_module( "globbartests.globfoo_test", [ "from unittest import TestCase", "", "class GlobFooTest(TestCase):", " def test_bar(self):", " pass", ], ) pf = PathFinder(basedir=modpath.basedir, prefix="*bar", module_name="*foo") r = list(pf.paths()) self.assertEqual(1, len(r)) r = pf._find_basename("*bar", ["globbartests"], is_prefix=True) self.assertEqual("globbartests", r) r = pf._find_basename("*bar", ["globbartests"], is_prefix=False) self.assertEqual("globbartests", r) r = pf._find_basename("*foo", ["globfoo_test.py", "__init__.py"], is_prefix=False) self.assertEqual("globfoo_test.py", r) r = pf._find_basename("*foo", ["globfoo_test.py", "__init__.py"], is_prefix=True) self.assertEqual("globfoo_test.py", r) pf = PathFinder(basedir=modpath.basedir, prefix="bar", module_name="foo") r = list(pf.paths()) self.assertEqual(0, len(r))
def test_fk(self): mpath = testdata.create_module([ "from prom import Field, Orm", "", "class Foo(Orm):", " pass", "", "class Bar(Orm):", " foo_id = Field(Foo, True)", "", "class Che(Orm):", " foo_id = Field(Foo, False)", " bar_id = Field(Bar, True)", "", "class Boo(Orm):", " pass", ]) Foo = mpath.module().Foo Bar = mpath.module().Bar Che = mpath.module().Che Boo = mpath.module().Boo b = Bar(foo_id=5) self.assertEqual(5, b.fk(Foo)) c = Che(foo_id=10, bar_id=20) self.assertEqual(10, c.fk(Foo)) self.assertEqual(20, c.fk(Bar)) c = Che() self.assertEqual(None, c.fk(Foo)) self.assertEqual(None, c.fk(Bar)) with self.assertRaises(ValueError): c.fk(Boo)
def test_unicode_output(self): mod1 = testdata.create_module("foo.bar.__main__", [ "import testdata", "print(testdata.get_unicode_words().encode('utf8'))", ]) r = testdata.run(mod1)
def test_encoding(self): m = testdata.create_module(contents=[ "# -*- coding: utf-8 -*-", "from __future__ import unicode_literals, division, print_function, absolute_import", ]) d = Dependencies(m.path)
def test_decorator_inherit_1(self): """make sure that a child class that hasn't defined a METHOD inherits the METHOD method from its parent with decorators in tact""" controller_prefix = "foodecinherit" m = testdata.create_module(controller_prefix, [ "import endpoints", "", "def foodec(func):", " def wrapper(*args, **kwargs):", " return func(*args, **kwargs)", " return wrapper", "", "class _BaseController(endpoints.Controller):", " @foodec", " def POST(self, **kwargs):", " return 1", "", "class Default(_BaseController):", " pass", "", ]) rs = self.create_reflect(controller_prefix) for count, endpoint in enumerate(rs, 1): self.assertEqual("foodec", endpoint.decorators["POST"][0].name) self.assertEqual(1, count)
def test_method_docblock(self): controller_prefix = "mdoc" testdata.create_module(controller_prefix, [ "import endpoints", "class Foo(endpoints.Controller):", " '''controller docblock'''", " def GET(*args, **kwargs):", " '''method docblock'''", " pass", "", ]) rs = self.create_reflect(controller_prefix) for endpoint in rs: desc = endpoint.methods['GET'][0].desc self.assertEqual("method docblock", desc)
def test_subquery_2(self): """Similar test as subquery_1 but makes sure query_class works as expected also""" count = 10 mpath = testdata.create_module([ "from prom import Field, Orm, Query", "", "class Foo(Orm):", " pass", "", "class BarQuery(Query):", " pass", "", "class Bar(Orm):", " foo_id = Field(Foo, True)", " query_class = BarQuery", ]) Foo = mpath.module().Foo Bar = mpath.module().Bar foo_ids = self.insert(Foo, count) for foo_id in foo_ids: Bar.create(foo_id=foo_id) q = Bar.query.in_foo_id(Foo.query.select_pk()) self.assertEqual(count, len(q.get()))
def test_subquery_1(self): count = 10 mpath = testdata.create_module([ "from prom import Field, Orm", "", "class Foo(Orm):", " pass", "", "class Bar(Orm):", " foo_id = Field(Foo, True)", ]) Foo = mpath.module().Foo Bar = mpath.module().Bar foo_ids = self.insert(Foo, count) for foo_id in foo_ids: Bar.create(foo_id=foo_id) q = Bar.query.in_foo_id(Foo.query.select_pk()) self.assertEqual(count, len(q.get())) q = Bar.query.in_foo_id(Foo.query.select_pk().gt_pk(count + 10000)) self.assertEqual(0, len(q.get())) q = Bar.query.is_foo_id(Foo.query.select_pk().limit(1)) self.assertEqual(1, len(q.get()))
def test_decorators(self): controller_prefix = "controller_reflect" testdata.create_module(controller_prefix, [ "import endpoints", "from endpoints.decorators import param", "", "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)", "", "class Foo(endpoints.Controller):", " @dec_func", " def GET(*args, **kwargs): pass", " @dec_cls", " @param('foo', default=1, type=int)", " @param('bar', type=bool, required=False)", " @param('che_empty', type=dict, default={})", " @param('che_full', type=dict, default={'key': 'val', 'key2': 2.0})", " @param('baz_empty', type=list, default=[])", " @param('baz_full', type=list, default=['val', False, 1])", " @param('d')", " def POST(*args, **kwargs): pass", "" ]) rs = self.create_reflect(controller_prefix) l = list(rs.controllers) r = l[0] methods = r.methods params = methods['POST'][0].params for p in ['d']: self.assertTrue(params[p]['required']) for p in ['foo', 'bar', 'che_empty', 'che_full', 'baz_empty', 'baz_full']: self.assertFalse(params[p]['required']) self.assertEqual(1, len(l)) self.assertEqual('/foo', r.uri) self.assertSetEqual(set(['GET', 'POST', 'OPTIONS']), set(r.methods.keys()))
def test_docblock(self): controller_prefix = "docblock" testdata.create_module(controller_prefix, [ "import endpoints", "class Foo(endpoints.Controller):", " '''this is a multiline docblock", "", " this means it has...", " ", " multiple lines", " '''", " def GET(*args, **kwargs): pass", "", ]) rs = self.create_reflect(controller_prefix) for endpoint in rs: self.assertTrue("\n" in endpoint.desc)
def test_decorators_param_help(self): controller_prefix = "dec_param_help" testdata.create_module(controller_prefix, [ "import endpoints", "from endpoints.decorators import param", "class Default(endpoints.Controller):", " @param('baz_full', type=list, default=['val', False, 1], help='baz_full')", " @param('d', help='d')", " def POST(*args, **kwargs): pass", "" ]) rs = self.create_reflect(controller_prefix) l = list(rs.controllers) r = l[0] methods = r.methods params = methods['POST'][0].params for k, v in params.items(): self.assertEqual(k, v['options']['help'])
def test_issue_24(self): """Turns out I can't fix this issue, so this test is kind of useless""" # trying to setup the environment according to: https://github.com/Jaymon/pyt/issues/24 raise self.skipTest("won't fix") basedir = testdata.create_dir() other_basedir = testdata.create_dir("other/directory", basedir) other_modpath = testdata.create_module( "i24tests.model24_test", [ "from unittest import TestCase", "", "class Issue24TestCase(TestCase):", " def test_boo(self):", " pass", ], other_basedir ) modpath = testdata.create_module( "i24tests.model24_test", [ "from unittest import TestCase", "", "class Issue24TestCase(TestCase):", " def test_boo(self):", " pass", ], basedir ) #pout.v(basedir, other_modpath.path, modpath.path) pf = PathFinder( basedir=basedir, module_name="model24", prefix="i24tests", class_name="Issue24", method_name="boo" ) r = list(pf.method_names()) self.assertEqual(2, len(r)) self.assertNotEqual(r[0], r[1])
def test_standard(self): """make sure standard modules are ignored""" m = testdata.create_module(contents=[ "import json", "import os", "import base64", ]) d = Dependencies(m.path) self.assertEqual(0, len(d))
def test_handle_404_typeerror_2(self): """make sure 404 works when a path bit is missing""" controller_prefix = "h404te2" contents = os.linesep.join([ "from endpoints import Controller", "class Default(Controller):", " def GET(self, needed_bit, **kwargs):", " return ''" ]) testdata.create_module(controller_prefix, contents=contents) r = endpoints.Request() r.method = u'GET' r.path = u'/' c = endpoints.Call(controller_prefix) c.request = r res = c.handle() res.body # we need to cause the body to be handled self.assertEqual(404, res.code)
def test_public_controller(self): contents = os.linesep.join([ "from endpoints import Controller", "class Bar(Controller):", " def get(*args, **kwargs): pass" ]) testdata.create_module("controller2.foo2", contents=contents) r = endpoints.Request() r.path = u"/foo2/bar" r.path_args = [u"foo2", u"bar"] r.query_kwargs = {u'foo2': u'bar', u'che': u'baz'} r.method = u"GET" c = endpoints.Call("controller2") c.request = r # if it succeeds, then it passed the test :) with self.assertRaises(endpoints.CallError): d = c.get_callback_info()
def test_callback_info(self): controller_prefix = "callback_info" req, res = self.get_http_instances("/foo/bar") req.query_kwargs = {'foo': 'bar', 'che': 'baz'} r = Router([controller_prefix]) with self.assertRaises(ImportError): d = r.find(req, res) contents = [ "from endpoints import Controller", "class Bar(Controller):", " def GET(*args, **kwargs): pass" ] testdata.create_module("{}.foo".format(controller_prefix), contents=contents) # if it succeeds, then it passed the test :) d = r.find(req, res)
def test_local_module(self): m = testdata.create_module(contents=[ "import boto3", "import os", "import sys", ]) d = Dependencies(m.path) self.assertLess(0, len(d))
def create_server(self, controller_prefix, contents, **kwargs): tdm = testdata.create_module(controller_prefix, contents) server = self.server_class(controller_prefix, host=self.get_host(), **kwargs) server.cwd = tdm.basedir server.stop() self.server = server self.server.start() return server
def test___init__(self): m = testdata.create_module(contents=[ "import foo1", "from foo2 import bar", "from foo3 import bar as che", "import foo4 as boo", "import foo5.zoo", "from foo6 import *", "from . import foo7, foo8", "from .foo12 import foo13", "from foo9 import foo10, foo11", "from che1 import (", " cheA,", " cheB,", " cheC,", ")", "import che2, che3", "", "def do():", " import bar1", " from bar2 import foo", " from bar3 import che as baz", ]) im = Imports(m.path) self.assertEqual(13, len(im)) for x in range(1, 7): self.assertTrue("foo{}".format(x) in im) for x in range(1, 4): self.assertTrue("bar{}".format(x) in im) for x in range(1, 4): self.assertTrue("che{}".format(x) in im) m = testdata.create_module(contents=[ "from .foo12 import foo13", "from foo14 import foo15", ]) im = Imports(m.path) self.assertEqual(1, len(im)) self.assertTrue("foo14" in im)
def test_ignore(self): m = testdata.create_module(contents=[ "import os", "import json", "import boto3", "import base64", "from botocore.exceptions import ClientError", ]) d = Dependencies(m.path, ["^boto3(?:\.|$)", "^botocore(?:\.|$)"]) self.assertEqual(0, len(d))
def test_default_match_with_path(self): """when the default controller is used, make sure it falls back to default class name if the path bit fails to be a controller class name""" controller_prefix = "nomodcontroller2" contents = os.linesep.join([ "from endpoints import Controller", "class Default(Controller):", " def GET(self, *args, **kwargs):", " return args[0]" ]) testdata.create_module("{}.nmcon".format(controller_prefix), contents=contents) c = endpoints.Call(controller_prefix) r = endpoints.Request() r.method = 'GET' r.path = '/nmcon/8' c.request = r res = c.handle() self.assertEqual('"8"', res.body)
def test_module(self): m = testdata.create_module("bar.foo_test", [ "from unittest import TestCase", "class FooTest(TestCase):", " def test_foo(self):", " pass", #" print 'in foo test'", "", ]) self.assertEqual(m.module.__file__, m.path) self.assertEqual("bar/foo_test.py", m.relpath)
def test_handle_accessdenied(self): """raising an AccessDenied error should set code to 401 and the correct header""" controller_prefix = "haccessdenied" contents = os.linesep.join([ "from endpoints import Controller, AccessDenied", "class Default(Controller):", " def GET(*args, **kwargs):", " raise AccessDenied('basic')", ]) testdata.create_module(controller_prefix, contents=contents) r = endpoints.Request() r.method = u'GET' r.path = u'/' c = endpoints.Call(controller_prefix) c.request = r res = c.handle() res.body # we need to cause the body to be handled self.assertEqual(401, res.code) self.assertTrue('Basic' in res.headers['WWW-Authenticate'])
def test_handle_redirect(self): contents = os.linesep.join([ "from endpoints import Controller, Redirect", "class Testredirect(Controller):", " def GET(*args, **kwargs):", " raise Redirect('http://example.com')" ]) testdata.create_module("controllerhr.handle", contents=contents) r = endpoints.Request() r.path = u"/handle/testredirect" r.path_args = [u'handle', u'testredirect'] r.query_kwargs = {} r.method = u"GET" c = endpoints.Call("controllerhr") c.request = r res = c.handle() res.body # we need to cause the body to be handled self.assertEqual(302, res.code) self.assertEqual('http://example.com', res.headers['Location'])
def test_ref(self): m = testdata.create_module([ "import prom", "class Foo(prom.Orm):", " che = prom.Field(str)", "", "class Bar(prom.Orm):", " foo_id = prom.Field(Foo)", "" ]) Foo = m.module().Foo Bar = m.module().Bar self.assertTrue(isinstance(Bar.schema.fields['foo_id'].schema, Schema)) self.assertTrue( issubclass(Bar.schema.fields['foo_id'].interface_type, long))
def test_directory(self): d = testdata.create_dir() self.assertEqual(d, d.directory) f = testdata.create_file("dir.txt", "", d) self.assertEqual(d, f.directory) p = testdata.create_package("r.e", "", d) self.assertEqual(os.path.join(d, "r", "e"), p.directory) m = testdata.create_module("d.i", "", d) self.assertEqual(os.path.join(d, "d"), m.directory)
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_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_callback_info(self): controller_prefix = "callback_info" r = endpoints.Request() r.path = u"/foo/bar" r.path_args = [u"foo", u"bar"] r.query_kwargs = {u'foo': u'bar', u'che': u'baz'} r.method = u"GET" c = endpoints.Call(controller_prefix) c.request = r with self.assertRaises(endpoints.CallError): d = c.get_callback_info() contents = os.linesep.join([ "from endpoints import Controller", "class Bar(Controller):", " def GET(*args, **kwargs): pass" ]) testdata.create_module("{}.foo".format(controller_prefix), contents=contents) # if it succeeds, then it passed the test :) d = 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( { "": [ "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_decorators(self): controller_prefix = "controller_reflect" testdata.create_module(controller_prefix, [ "import endpoints", "from endpoints.decorators import param", "", "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)", "", "class Foo(endpoints.Controller):", " @dec_func", " def GET(*args, **kwargs): pass", " @dec_cls", " @param('foo', default=1, type=int)", " @param('bar', type=bool, required=False)", " @param('che_empty', type=dict, default={})", " @param('che_full', type=dict, default={'key': 'val', 'key2': 2.0})", " @param('baz_empty', type=list, default=[])", " @param('baz_full', type=list, default=['val', False, 1])", " @param('d')", " def POST(*args, **kwargs): pass", "" ]) rs = self.create_reflect(controller_prefix) l = list(rs.controllers) r = l[0] methods = r.methods params = methods['POST'][0].params for p in ['d']: self.assertTrue(params[p]['required']) for p in [ 'foo', 'bar', 'che_empty', 'che_full', 'baz_empty', 'baz_full' ]: self.assertFalse(params[p]['required']) self.assertEqual(1, len(l)) self.assertEqual('/foo', r.uri) self.assertSetEqual(set(['GET', 'POST', 'OPTIONS']), set(r.methods.keys()))
def __init__(self, controller_prefix, module_body, config_module_body='', host=''): self.cwd = testdata.create_dir() self.client = self.client_class(host) # create the controller module self.module_path = testdata.create_module(controller_prefix, module_body, self.cwd) # now create the server script self.script_path = testdata.create_file( self.server_script_name, os.linesep.join([ "import os", "import sys", "import logging", "logging.basicConfig(", " format=\"[%(levelname).1s] %(message)s\",", " level=logging.DEBUG,", " stream=sys.stdout", ")", #"sys.path.append('{}')".format(os.path.dirname(os.path.realpath(inspect.getsourcefile(endpoints)))), "sys.path.append('{}')".format(os.path.realpath(os.curdir)), "", #"from endpoints.interface.wsgi import *", "from endpoints.interface.wsgi import Application, Server", "" "os.environ['ENDPOINTS_PREFIX'] = '{}'".format( controller_prefix), "", "##############################################################", os.linesep.join(config_module_body), "##############################################################", #os.linesep.join(self.get_script_body()), "#from wsgiref.validate import validator", "#application = validator(Application())", "application = Application()", "" ]), self.cwd) # server self.server = self.server_class(controller_prefix=controller_prefix, host=host, wsgifile=self.script_path) self.server.cwd = self.cwd self.server.start()
def __init__(self, contents): module_info = testdata.create_module(contents=contents) self.directory = module_info.basedir self.module = module_info.module self.message_classes = [] clear_names = {} for _, message_class in inspect.getmembers(self.module, inspect.isclass): if issubclass(message_class, Message): clear_names[message_class.get_name()] = message_class self.message_classes.append(message_class) for message_class in clear_names.values(): message_class.clear()
def __init__(self, modulepath, contents): module_info = testdata.create_module(modulepath, contents=contents) self.directory = module_info.basedir self.module = module_info.module self.message_classes = [] clear_names = {} for _, message_class in inspect.getmembers(self.module, inspect.isclass): if issubclass(message_class, Message): clear_names[message_class.get_name()] = message_class self.message_classes.append(message_class) for message_class in clear_names.values(): message_class.clear()
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_multi_methods(self): controller_prefix = "multi_methods" mp = testdata.create_module(controller_prefix, [ "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_version1(self): pass", "", " @version('v2')", " def GET_version2(self): pass", "" ]) rc = ReflectController(controller_prefix, mp.module.Bar) self.assertEqual(2, len(rc.methods["GET"])) for rm in rc.methods["GET"]: self.assertTrue(rm.version in ["v1", "v2"])