def test_main_multiline(self): contents = "\n".join([ "virtual_alias_map = hash:/some/path/one,", " hash:/some/path/two,", " hash:/some/path/three", ]) path = testdata.create_file("main.cf", contents) c = postfix.Main(prototype_path=path) self.assertEqual(contents, str(c)) contents = "\n".join([ "virtual_alias_map = hash:/some/path/one,", " hash:/some/path/two,", " hash:/some/path/three", "virtual_alias_domains = /another/path/and/stuff", ]) path = testdata.create_file("main.cf", contents) c = postfix.Main(prototype_path=path) self.assertEqual(contents, str(c)) c["virtual_alias_map"] = c["virtual_alias_map"].val + "\n hash:/some/path/four" contents = "\n".join([ "virtual_alias_map = hash:/some/path/one,", " hash:/some/path/two,", " hash:/some/path/three", " hash:/some/path/four", "virtual_alias_domains = /another/path/and/stuff", ]) self.assertEqual(contents, str(c))
def test_update_domain_proxy(self): # to make sure this works completely, we completely remove postfix p = Postfix() p.reset() f = testdata.create_file("foo.com", [ "[email protected] [email protected]", "", ]) s = Stockton("add-domain") r = s.run("{} --proxy-file={}".format(f.name, f)) m = Main(prototype_path=Main.dest_path) proxy_path = re.search("^hash:([/a-z]+?foo\.com)$", m["virtual_alias_maps"].val, re.M).group(1) proxy_path_f = Filepath(proxy_path) self.assertTrue("*****@*****.**" in proxy_path_f.contents()) s = Stockton("update-domain-proxy") f = testdata.create_file("foo.com", [ "[email protected] [email protected]", "", ]) r = s.run("{} --proxy-file={}".format(f.name, f)) m = Main(prototype_path=Main.dest_path) proxy_path = re.search("^hash:([/a-z]+?foo\.com)$", m["virtual_alias_maps"].val, re.M).group(1) proxy_path_f = Filepath(proxy_path) self.assertFalse("*****@*****.**" in proxy_path_f.contents()) self.assertTrue("*****@*****.**" in proxy_path_f.contents())
def test_copy_into(self): # directory into directory source_d = testdata.create_files({ "foo.txt": testdata.get_words(), "bar/che.txt": testdata.get_words(), }) d = testdata.create_dir() d.copy_into(source_d) self.assertTrue("foo.txt" in d) self.assertTrue("bar/che.txt" in d) source_f = testdata.create_file("foo.txt", testdata.get_words()) # file into directory d = testdata.create_dir() d.copy_into(source_f) self.assertTrue(source_f.basename in d) dest_f = d.get_file(source_f.basename) self.assertEqual(source_f.contents(), dest_f.contents()) # file into file dest_f = testdata.create_file("foo.txt", testdata.get_words()) self.assertNotEqual(source_f.contents(), dest_f.contents()) dest_f.copy_into(source_f) self.assertEqual(source_f.contents(), dest_f.contents()) self.assertTrue(source_f.contents() in dest_f.contents())
def test_master_section_commented(self): contents = "#smtps inet n - - - - smtpd" master_path = testdata.create_file("master.cf", contents) master = postfix.Master(prototype_path=master_path) master["smtps"].modified = True self.assertEqual("smtps inet n - - - - smtpd", str(master))
def test_master_section_modify_option(self): master_path = testdata.create_file("master.cf", "\n".join([ "#submission inet n - - - - smtpd", "# -o syslog_name=postfix/submission", "# -o smtpd_tls_security_level=encrypt", "# -o smtpd_sasl_auth_enable=yes", "# -o smtpd_reject_unlisted_recipient=no", "# -o smtpd_client_restrictions=one", "# -o smtpd_helo_restrictions=two", "# -o smtpd_sender_restrictions=three", "# -o smtpd_recipient_restrictions=", "# -o smtpd_relay_restrictions=permit_sasl_authenticated,reject", "# -o milter_macro_daemon_name=ORIGINATING" ])) m = postfix.Master(prototype_path=master_path) m["submission"].modified = True m["submission"].update( ("syslog_name", "postfix/submission"), ("smtpd_tls_security_level", "may"), ("smtpd_tls_cert_file", "/foo/bar.pem"), ("smtpd_sasl_auth_enable", "yes"), ("smtpd_reject_unlisted_recipient", "no"), ("smtpd_relay_restrictions", "permit_sasl_authenticated,reject"), ("milter_macro_daemon_name", "ORIGINATING") ) self.assertEqual(4, str(m).count("#")) self.assertEqual(11, len(m["submission"].options))
def test_change_interface(self): class InterTorm(Orm): connection_name = "change-interface" #connection_name = "" pass path = testdata.create_file("inter1.db") dsn = "sqlite://{}#{}".format(path, InterTorm.connection_name) configure(dsn) InterTorm.install() self.assertTrue(InterTorm.interface.has_table(InterTorm.table_name)) path = testdata.create_file("inter2.db") dsn = "sqlite://{}#{}".format(path, InterTorm.connection_name) configure(dsn) self.assertFalse(InterTorm.interface.has_table(InterTorm.table_name))
def create_server(self, controller_prefix, contents, config_contents='', **kwargs): wsgifile = testdata.create_file("wsgifile.py", [ "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.realpath(os.curdir)), "", "import gevent", "import gevent.monkey", "if not gevent.monkey.saved:", " gevent.monkey.patch_all()", "" "from endpoints.interface.uwsgi.async import WebsocketApplication as Application", "os.environ['ENDPOINTS_PREFIX'] = '{}'".format(controller_prefix), "", "##############################################################", "\n".join(config_contents), "##############################################################", #os.linesep.join(self.get_script_body()), "#from wsgiref.validate import validator", "#application = validator(Application())", "application = Application()", "" ]) return super(WebsocketTest, self).create_server( controller_prefix, contents, wsgifile=wsgifile, )
def test_html_file(self): path = testdata.create_file("bodies-html.txt", [ "<p>text</p>", ]) bods = Bodies([path]) for bod in bods: self.assertEqual("<p>text</p>", bod)
def test_chunked(self): filepath = testdata.create_file("filename.txt", testdata.get_words(500)) controller_prefix = 'wsgi.post_chunked' c = self.create_client(controller_prefix, [ "import hashlib", "from endpoints import Controller", "class Bodykwargs(Controller):", " def POST(self, **kwargs):", " return hashlib.md5(kwargs['file'].file.read()).hexdigest()", "", "class Bodyraw(Controller):", " def POST(self, **kwargs):", " return len(self.request.body)", "", ]) size = c.post_chunked('/bodyraw', { "foo": "bar", "baz": "che" }, filepath=filepath) self.assertGreater(int(size), 0) with codecs.open(filepath, "rb", encoding="UTF-8") as fp: h1 = hashlib.md5(fp.read().encode("UTF-8")).hexdigest() h2 = c.post_chunked('/bodykwargs', { "foo": "bar", "baz": "che" }, filepath=filepath) self.assertEqual(h1, h2.strip('"'))
def test_return_code(self): path1 = testdata.create_file("foo.py", ["print('foo')", "exit(1)"]) r = testdata.run(path1, code=1) self.assertTrue("foo" in r) with self.assertRaises(RuntimeError): r = testdata.run(path1)
def xtest_fetch_foo(self): filename = "" m = self.cache_json( "http://www.businessinsider.com/lularoe-is-making-millennial-moms-rich-2016-9", filename) path = testdata.create_file("{}.html".format(filename), m.fields["content"]) pout.v(path)
def test_existing_file_creation(self): path = testdata.create_dir() d2 = testdata.create_dir(path) self.assertEqual(path, d2) relpath = "/foo1/bar1/test.txt" s = "happy" f = testdata.create_file(relpath, s)
def test_has_shared_library(self): modpath = testdata.create_package(contents=[]) shared_library = testdata.create_file("foo.so", tmpdir=modpath.directory) ps = Packages() p = ps[modpath] self.assertTrue(p.has_shared_library())
def test_run_file(self): path1 = testdata.create_file("foo.py", "print(1)") path2 = testdata.get_file(path1.fileroot, tmpdir=path1.basedir) r1 = testdata.run(path1) r2 = testdata.run(path2) r3 = path1.run() r4 = path2.run() self.assertTrue(r1 == r2 == r3 == r4)
def test_main_oneline(self): contents = "\n".join([ "virtual_alias_map = hash:/some/path/one", "foo = bar", "che = baz", ]) path = testdata.create_file("main.cf", contents) c = postfix.Main(prototype_path=path) self.assertEqual(contents, str(c))
def test_body_file(self): r = Response() self.assertFalse("Content-Type" in r.headers) self.assertFalse("Content-Length" in r.headers) path = testdata.create_file("foo.jpg", "12345") with path.open() as fp: r.body = fp mt = r.headers["Content-Type"] fs = r.headers["Content-Length"] self.assertEqual("image/jpeg", mt) self.assertEqual(5, int(fs)) path = testdata.create_file("foo.txt", "123") with path.open() as fp: r.body = fp mt = r.headers["Content-Type"] fs = r.headers["Content-Length"] self.assertEqual("text/plain", mt) self.assertEqual(3, int(fs))
def test_master_sections(self): contents = "\n".join([ "one inet n - - - - smtpd", " -o smtpd_tls_wrappermode=yes", "two inet n - - - - qmqpd", "three fifo n - - 60 1 pickup", ]) master_path = testdata.create_file("master.cf", contents) master = postfix.Master(prototype_path=master_path) self.assertEqual(contents, str(master))
def test_url_file(self): s = set(["foo", "bar", "che"]) with Webserver.start({"{}.html".format(k): k for k in s}) as w: # make sure whitespace is ignored path = testdata.create_file("bodies-url.txt", ["\n{}\n\n".format(w.url("{}.html".format(k))) for k in s]) bods = Bodies([path]) s2 = set(s) for bod in bods: self.assertTrue(bod in s2) s2.discard(bod) self.assertFalse(s2) path = testdata.create_file("bodies-url.txt", [w.url("{}.html".format(k)) for k in s]) bods = Bodies([path]) s2 = set(s) for bod in bods: self.assertTrue(bod in s2) s2.discard(bod) self.assertFalse(s2)
def test_stderr(self): filepath = testdata.create_file("errpipe.sh", [ 'echo "1" 1>&2', '(>&2 echo "2")', 'echo "3" >&2' ]) os.chmod(filepath, 0o755) #cmd = "echo 'foobar' 1>&2" #cmd = "/vagrant/errpipe.sh" output = cli.run(filepath) for x in range(1, 4): self.assertTrue(str(x) in output)
def test_update_before(self): contents = "\n".join([ "foo = 1", "baz = 3", ]) path = testdata.create_file("update_before.conf", contents) conf = Config(prototype_path=path) conf.update_before("baz", ("bar", 2)) self.assertTrue("foo" in str(conf.lines[0])) self.assertTrue("bar" in str(conf.lines[1])) self.assertTrue("baz" in str(conf.lines[2]))
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 test_create(self): d = testdata.create_dir() fex = testdata.create_file("create_exists", "foo", d) f = Filepath(fex) self.assertTrue(f.exists()) f.create() self.assertTrue("foo" in f.lines()) f = Filepath(d, "create_not_exists") self.assertFalse(f.exists()) f.create() self.assertTrue(f.exists()) self.assertFalse("foo" in f.lines())
def get_encrypted_interface(self): """get a connected interface""" config = DsnConnection(os.environ['MORP_DSN_1']) if testdata.random.randint(0, 1): key_path = testdata.create_file("/morp.key", testdata.get_ascii(100)) config.options['keyfile'] = key_path else: config.options['key'] = testdata.get_ascii(32) i = self.interface_class(config) i.connect() self.assertTrue(i.connected) return i
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 test_master_section_append_option(self): master_path = testdata.create_file("master.cf", "\n".join([ "smtp inet n - - - - smtpd", " -o foo=yes", ])) master = postfix.Master(prototype_path=master_path) contents = "\n".join([ "smtp inet n - - - - smtpd", " -o foo=yes", " -o bar=yes", ]) master["smtp"]["bar"] = "yes" self.assertEqual(contents, str(master))
def test_key(self): c = Connection() self.assertEqual("", c.key) self.assertEqual(c.key, c.key) key = testdata.get_ascii(100) c = Connection(options=dict(key=key)) self.assertNotEqual(b"", ByteString(c.key)) self.assertEqual(c.key, c.key) key_path = testdata.create_file("morp.key", testdata.get_ascii(100)) c = Connection(options=dict(key=key_path)) self.assertNotEqual(b"", ByteString(c.key)) self.assertEqual(c.key, c.key)
def test_post_file(self): filepath = testdata.create_file("json_post_file.txt", "json post file") controller_prefix = 'jsonclient.controller' server = self.create_server(controller_prefix, [ "from endpoints import Controller, decorators", "class Default(Controller):", " @decorators.param('file')", " def POST(self, *args, **kwargs):", " return dict(body=kwargs['file'].filename)", "", ]) c = self.create_client() r = c.post_file('/', {"foo": "bar", "baz": "che"}, {"file": filepath}) self.assertEqual(200, r.code) self.assertEqual("json_post_file.txt", r._body["body"])
def test_post_file(self): filepath = testdata.create_file("filename.txt", "this is a text file to upload") controller_prefix = 'wsgi.post_file' c = self.create_client(controller_prefix, [ "from endpoints import Controller", "class Default(Controller):", " def POST(self, *args, **kwargs):", " return kwargs['file'].filename", "", ]) r = c.post_file('/', {"foo": "bar", "baz": "che"}, {"file": filepath}) self.assertEqual(200, r.code) self.assertTrue("filename.txt" in r.body)
def get_encrypted_interface(self, config=None): """get a connected interface""" options = {} if testdata.yes(): options['key'] = testdata.create_file("/morp.key", testdata.get_ascii(100)) else: options['key'] = testdata.get_ascii(testdata.get_int(10, 200)) if config: for k, v in options.items(): config.options[k] = v else: config = self.get_config(**options) return self.get_interface(config)
def test_post_file_simple(self): filepath = testdata.create_file("filename.txt", "this is a text file to upload") controller_prefix = 'wsgi.post_file' server = self.create_server(controller_prefix, [ "from endpoints import Controller", "class Default(Controller):", " def POST(self, *args, **kwargs):", " return kwargs['file'].filename", "", ]) c = self.create_client() r = c.post_file('/', {"foo": "bar", "baz": "che"}, {"file": filepath}) self.assertEqual(200, r.code) self.assertTrue("filename.txt" in r.body)
def test_main_update(self): contents = "\n".join([ "foo = bar", "che = baz", ]) path = testdata.create_file("main.cf", contents) c = postfix.Main(dest_path=path, prototype_path=path) c.update( ("foo", "rab") ) c.save() c2 = postfix.Main(dest_path=path, prototype_path=path) self.assertEqual("rab", c2["foo"].val) self.assertEqual("baz", c2["che"].val)
def create_server(self, controller_prefix, contents, config_contents='', **kwargs): tdm = testdata.create_module(controller_prefix, contents) kwargs["controller_prefix"] = controller_prefix kwargs["host"] = self.get_host() if config_contents: config_path = testdata.create_file("config.py", config_contents) kwargs["wsgifile"] = config_path server = self.server_class(**kwargs) server.cwd = tdm.basedir server.stop() self.server = server self.server.start() return server
def test_add_domain_proxy_file_no_smtp(self): # to make sure this works completely, we completely remove postfix p = Postfix() p.reset() s = Stockton("add-domain") proxy_domains = testdata.create_files({ "foo.com": "\n".join([ "[email protected] [email protected]", "[email protected] [email protected]", "[email protected] [email protected]", "", ]), "bar.com": "\n".join([ "[email protected] [email protected]", "[email protected] [email protected]", "[email protected] [email protected]", "", ]), }) for f in proxy_domains: r = s.run("{} --proxy-file={}".format(f.name, f)) contents = "\n".join([ "@foo.com [email protected]", "", ]) f = testdata.create_file("foo.com", contents) r = s.run("{} --proxy-file={}".format(f.name, f)) foo = Filepath("/etc/postfix/virtual/addresses/foo.com") self.assertEqual(contents, foo.contents()) # Let's check structure because I was having a lot of problems with getting # the structure... # domains file should have 2 domains in it domains_f = Filepath("/etc/postfix/virtual/domains") self.assertEqual(2, domains_f.lc()) self.assertTrue(domains_f.contains("^foo\.com$")) m = Main(prototype_path=Main.dest_path) # we can't guarrantee foo, bar order so we match one line at a time self.assertTrue(re.search("^hash:[/a-z]+?(bar|foo)\.com,", m["virtual_alias_maps"].val, re.M)) self.assertTrue(re.search("^\s+hash:[/a-z]+?(bar|foo)\.com$", m["virtual_alias_maps"].val, re.M))
def test_master_section_manipulate_option(self): master_path = testdata.create_file("master.cf", "\n".join([ "smtp inet n - - - - smtpd", " -o foo=yes", " -o bar=yes", ])) master = postfix.Master(prototype_path=master_path) self.assertTrue(isinstance(master["smtp"], postfix.MasterSection)) contents = "\n".join([ "smtp inet n - - - - smtpd", " -o foo=no", " -o bar=yes", ]) master["smtp"]["foo"] = "no" self.assertEqual(contents, str(master))
def test__parse(self): path = testdata.create_file("space.conf", "\n".join([ "# Log to syslog", "Syslog yes", "# Required to use local socket with MTAs that access the socket as a non-", "# privileged user (e.g. Postfix)", "UMask 002", "", "# Sign for example.com with key in /etc/mail/dkim.key using", "# selector '2007' (e.g. 2007._domainkey.example.com)", "#Domain example.com", ])) c = generic.SpaceConfig(prototype_path=path) self.assertTrue(c["syslog"]) self.assertTrue(c["UMask"]) self.assertTrue(c["Domain"])
def test_post_file_with_param(self): """make sure specifying a param for the file upload works as expected""" filepath = testdata.create_file("post_file_with_param.txt", "post_file_with_param") controller_prefix = 'wsgi.post_file_with_param' server = self.create_server(controller_prefix, [ "from endpoints import Controller, decorators", "class Default(Controller):", " @decorators.param('file')", " def POST(self, *args, **kwargs):", " return kwargs['file'].filename", "", ]) c = self.create_client() r = c.post_file('/', {"foo": "bar", "baz": "che"}, {"file": filepath}) self.assertEqual(200, r.code) self.assertTrue("post_file_with_param.txt" in r.body)
def test_local(self): contents = "\n".join([ "#loadplugin Mail::SpamAssassin::Plugin::DCC", "loadplugin Mail::SpamAssassin::Plugin::Pyzor", "loadplugin Mail::SpamAssassin::Plugin::Razor2", ]) path = testdata.create_file("v310.pre", contents) c = spamassassin.Local(prototype_path=path) c.update(("loadplugin", "Mail::SpamAssassin::Plugin::DCC"),) contents = "\n".join([ "loadplugin Mail::SpamAssassin::Plugin::DCC", "loadplugin Mail::SpamAssassin::Plugin::Pyzor", "loadplugin Mail::SpamAssassin::Plugin::Razor2", ]) self.assertEqual(contents, str(c))
def test_copy_to(self): """https://github.com/Jaymon/testdata/issues/30""" source_d = testdata.create_files({ "foo.txt": testdata.get_words(), "bar/che.txt": testdata.get_words(), }) dest_d = testdata.create_dir() source_d.copy_to(dest_d) self.assertTrue("foo.txt" in dest_d) self.assertTrue("bar/che.txt" in dest_d) source_f = testdata.create_file("foo.txt", testdata.get_words()) dest_f = testdata.get_file() self.assertFalse(dest_f.exists()) source_f.copy_to(dest_f) self.assertEqual(source_f.contents(), dest_f.contents())
def test_file_stream(self): content = "this is a text file to stream" filepath = testdata.create_file("filename.txt", content) controller_prefix = 'wsgi.post_file' c = self.create_client(controller_prefix, [ "from endpoints import Controller", "class Default(Controller):", " def GET(self, *args, **kwargs):", " f = open('{}')".format(filepath), " self.response.set_header('content-type', 'text/plain')", " return f", "", ]) r = c.get('/') self.assertEqual(200, r.code) self.assertEqual(content, r.body)
def test_post_file_with_param(self): """make sure specifying a param for the file upload works as expected""" filepath = testdata.create_file("post_file_with_param.txt", "post_file_with_param") controller_prefix = 'wsgi.post_file_with_param' c = self.create_client(controller_prefix, [ "from endpoints import Controller, decorators", "class Default(Controller):", " @decorators.param('file')", " def POST(self, *args, **kwargs):", " return kwargs['file'].filename", "", ]) r = c.post_file('/', {"foo": "bar", "baz": "che"}, {"file": filepath}) self.assertEqual(200, r.code) self.assertTrue("post_file_with_param.txt" in r.body)
def create_server(self, contents, config_contents='', **kwargs): tdm = testdata.create_module(kwargs.get("controller_prefix", ""), contents) kwargs["controller_prefix"] = tdm kwargs["host"] = self.get_host() kwargs["cwd"] = tdm.basedir if config_contents: config_path = testdata.create_file( "{}.py".format(testdata.get_module_name()), config_contents) kwargs["config_path"] = config_path server = self.server_class(**kwargs) server.stop() server.start() self.server = server return server
def test_permissions(self): f = testdata.create_file("permissions.txt") self.assertRegexpMatches(f.permissions, "0[0-7]{3}") f.chmod("0755") self.assertEqual("0755", f.permissions) f.chmod(644) self.assertEqual("0644", f.permissions) f.chmod("655") self.assertEqual("0655", f.permissions) f.chmod(655) self.assertEqual("0655", f.permissions) f.chmod(500) self.assertEqual("0500", f.permissions)
def test_pyc_issues(self): """https://github.com/Jaymon/pyt/issues/34""" m = TestModule( "from unittest import TestCase", "class FooTest(TestCase):", " def test_bar(self): pass", ) pyc_f = testdata.create_file("{}.pyc".format(m.module.name), "", tmpdir=m.module.parent.directory) tl = m.loader s = tl.loadTestsFromName("{}.Foo".format(m.module_name)) self.assertEqual(1, len(s._tests[0]._tests)) self.assertTrue( inspect.getsourcefile( s._tests[0]._tests[0].__class__).endswith(".py"))
def test_key(self): c = Connection() self.assertEqual("", c.key) self.assertEqual(c.key, c.key) key = testdata.get_ascii(100) c = Connection(options=dict(key=key)) self.assertNotEqual(b"", b"{}".format(c.key)) self.assertEqual(c.key, c.key) key_path = testdata.create_file("morp.key", testdata.get_ascii(100)) c = Connection(options=dict(keyfile=key_path)) self.assertNotEqual(b"", b"{}".format(c.key)) self.assertEqual(c.key, c.key) c = Connection(options=dict(key=key, keyfile=key_path)) self.assertNotEqual(b"", b"{}".format(c.key)) c2 = Connection(options=dict(key=key, keyfile=key_path)) self.assertEqual(c.key, c2.key)
def get_lambda(cls, name="herd_unittests", contents=None, environ=None): if not contents: contents = [ "def handler(event, context):", " '''Autogenerated lambda for herd unit tests, this can be safely deleted", " but herd will re-create it if the unit tests are ran again'''", " return {", " 'statusCode': 200,", " 'body': 1", " }", ] filename = testdata.get_filename(name=name, ext="py") filepath = testdata.create_file(path=filename, contents=contents) r = cls.get_role() r.save() l = Lambda(filepath, role=r, environ=environ) l.save() return l
def test_wsgifile(self): wsgifile = testdata.create_file("wsgiserverapp.py", [ "import os", "from endpoints.interface.wsgi import Application", "os.environ['WSGI_TESTING'] = 'foo bar'", "application = Application()", "", ]) controller_prefix = 'wsgiservercon.controller' server = self.create_server(controller_prefix, [ "import os", "from endpoints import Controller, decorators", "class Default(Controller):", " def GET(self):", " return os.environ['WSGI_TESTING']", "", ], wsgifile=wsgifile) c = self.create_client() r = c.get("/") self.assertEqual(200, r.code) self.assertEqual("foo bar", r._body)
def test_bundle_dependencies(self): m = testdata.create_module(contents="import sys, os") filepath = testdata.create_file(testdata.get_filename("py"), contents=[ "import boto3", "import {}".format(m), "import email", "", "def handler(event, context):", " pass", ]) l = Lambda(filepath, role=self.get_role()) zip_path = l.bundle() with testdata.capture(True) as c: with ZipFile(zip_path, 'r') as z: z.printdir() self.assertTrue(filepath.basename in c) self.assertTrue(m in c) self.assertTrue("boto3" in c)
def test_crud(self): """!!! This writes to AWS""" role = self.get_role() role.save() m = testdata.create_module(contents="import sys, os") filename = testdata.get_filename("py") contents = [ "import testdata", "import json", "import {}".format(m), "", "def handler(event, context):", " '''herd unit test function, this can be safely deleted'''", " return {", " 'statusCode': 200,", " 'body': \"1\"", " }", ] filepath = testdata.create_file(filename, contents=contents) l = Lambda(filepath, role=role) l.save() r = l.run() self.assertEqual(200, r["statusCode"]) self.assertEqual("1", r["body"]) contents[-2] = " 'body': \"2\"" filepath.replace(contents) l.save() r = l.run() self.assertEqual(200, r["statusCode"]) self.assertEqual("2", r["body"]) l.delete()