def test_other(): ok(core.curr_os()) == 'ubuntu' with mock.patch('fablib.core.run', lambda x : 1 / 0): with mock.patch('fablib.core.sudo', lambda x : 1 / 0): # no system call should be made ok(core.curr_os()) == 'ubuntu'
def _(self): slug = 'albert-einstein' self.request.matchdict = {'slug': slug} response = details_view(self.request) ok(response['error']) == None ok(response['item']) == einstein
def test_get_put(): with warnings.catch_warnings(): fname = os.tmpnam() t1 = 'some data' t2 = 'other text' core.put_rf(fname, t1) try: ok(core.get_rf(fname)) == t1 sudo('chown root.root ' + fname) sudo('chmod o-w ' + fname) ok(lambda : core.put_rf(fname, t2)).raises(SystemExit) core.put_rf(fname, t2, use_sudo=True) ok(core.get_rf(fname)) == t2 with core.remote_fl(fname, use_sudo=True) as fc: ok(fc.getvalue()) == t2 fc.setvalue(t1) ok(core.get_rf(fname)) == t1 finally: sudo('rm ' + fname)
def t9(self): class Foo: def bar(self): return 'bar' class Delegate: def action(self): f = Foo() return f.bar() rd_bar = redef(Foo, 'bar', lambda s: 'baz') ok(rd_bar.not_called()) == True captured = stderr_of(Redef.__del__, rd_bar) ok(captured.output) == 'redef\'d function \'bar\' was not called and should have been called.\n\tMis-called redefs could be due to test crashes unless explicitly tested using Redef kwargs: must_call\n\ttest_redef.py:152: rd_bar = redef(Foo, \'bar\', lambda s: \'baz\')\n' wt_bar = wiretap(Foo, 'bar', must_call=False) rd_a = redef(Delegate, 'action', lambda s: 'rainbows!') Delegate().action() ok(wt_bar.not_called()) == True captured = stderr_of(Redef.__del__, wt_bar) ok(captured.output) == '' wt_bar2 = wiretap(Foo, 'bar', must_call=False) Foo().bar() captured = stderr_of(Redef.__del__, wt_bar2) ok(captured.output) == 'redef\'d function \'bar\' was called and should not have been called.\n\tMis-called redefs could be due to test crashes unless explicitly tested using Redef kwargs: must_call\n\ttest_redef.py:164: wt_bar2 = wiretap(Foo, \'bar\', must_call=False)\n'
def t11(self): import string with redef(string, 'hexdigits', 'orange'): replaced = string.hexdigits ok(replaced) == 'orange' replaced = string.hexdigits ok(replaced) == '0123456789abcdefABCDEF'
def _(self): result = self.p.person(self.id).delete() ok(result) == True def f(): self.p.person(self.id).delete() ok (f).raises(HttpClientError)
def _(self): with requests_mock.mock() as m: m.get("{0}generations".format(self.m.base_endpoint), text='{"1": {"active": true, "description": "Initial import", "id": 1, "created": "2014-12-15T15:13:29.568"},' ' "2": {"active": true, "description": "Second generation.", "id": 2, "created": "2015-02-28T23:30:15.954"}}') r = self.m.is_online() ok(m.called ) == True
def _(self): class A: """Base class""" def a(self, x): return x * 2 class B(A): def a(self, x): ret = A.a(self, x) return "b" + ret bee = B() ok(bee.a("z")) == "bzz" want = "baa baa" rd_b = redef(B, "a", lambda s, x: want) ok(bee.a("z")) == "baa baa" ok(rd_b.called()) == 1 del rd_b want = "atter batter" rd_a = redef(A, "a", lambda s, x: want) ok(bee.a("z")) == "batter batter" ok(rd_a.called()) == 1
def _i(self): try: with ConfigRoot(prod, [prod]) as cr: cr.ConfigItems(prod="hello") ConfigItem(repeat=True) fail ("Expected exception") except ConfigException as ex: ok (ex.message) == "'ConfigItems' is defined both as simple value and a contained item: ConfigItem {\n}"
def test_ssh_executor1(self): id_rsa_path = os.path.expanduser('~/.ssh/id_rsa') ssh_url = "ssh://localhost::" + id_rsa_path expected = sorted(os.listdir('/')) conn = ssh_utils.connect(ssh_url) out = ssh_utils.run_over_ssh(conn, "ls /") ok(sorted(out.split())) == expected
def _(self): for records in self.records: for record in records: ok (record).contains('title') ok (record).contains('snippet') ok (record).contains('publish_date') ok (record).contains('source') ok (record).contains('authors')
def _(self): for records in self.records: for record in records: ok (len(record['title'])) > 0 ok (len(record['snippet'])) > 0 ok (record['source']).is_a(unicode) ok (len(record['authors'])) > 0 ok (record['publish_date']).is_a(date)
def test_time_estimate(self): sections = P(self.code_test_cycles, {'RUNTIME': 20}) sections = list(sections) etime = agent.calculate_execution_time(sections) ok(etime) == 20 * 4 + 20 * 2 + 40 * 2 ok(agent.sec_to_str(etime)) == "0:03:20"
def _k(self): cr = ConfigRoot(prod, [prod]) try: print cr.b fail ("Expected exception") except ConfigException as ex: ok (ex.message) == "ConfigRoot {\n} has no attribute 'b'"
def _(self): def createExtends(): class PropertyExtend(PropertyOwner): """ 継承して@getterを付けてみる """ @x.getter def x(self): return self._x return PropertyExtend() ok(createExtends).raises(NameError)
def t12(self): class Foo: def bar(self, x): return x * 3 rd_foo = redef(Foo, 'bar', lambda s,x: x**3 ) x = Foo() ok(x.bar(3)) == 27 rd_foo.close() ok(x.bar(3)) == 9
def t10(self): import string rd_hexdigits = redef(string, 'hexdigits', 'orange') replaced = string.hexdigits ok(replaced) == 'orange' del rd_hexdigits replaced = string.hexdigits ok(replaced) == '0123456789abcdefABCDEF'
def _k(self): try: with ConfigRoot(prod, [prod]) as cr: ConfigItem(repeat=False) errorline = lineno() + 1 ConfigItem(repeat=False) fail ("Expected exception") except ConfigException as ex: ok (ex.message) == "Repeated non repeatable conf item: 'ConfigItem'"
def _a(self): @required('anattr, anotherattr') class root(ConfigRoot): pass with root(prod, [prod]) as cr: cr.anattr(prod=1) cr.anotherattr(prod=2) ok (cr.anattr) == 1 ok (cr.anotherattr) == 2
def _e(self): try: with dummy.dummy_io('stdin not used') as d_io: with ConfigRoot(prod, [prod]) as cr: errorline = lineno() + 1 cr.a(pros="hello", prod="hi") fail ("Expected exception") except ConfigException as ex: sout, serr = d_io ok (serr) == ce(errorline, "No such Env or EnvGroup: 'pros'") ok (ex.message) == "There were 1 errors when defining attribute 'a'"
def _f(self): try: with dummy.dummy_io('stdin not used') as d_io: with ConfigRoot(prod, [prod, pp]) as cr: errorline = lineno() + 1 cr.a(prod="hello") fail ("Expected exception") except ConfigException as ex: sout, serr = d_io ok (serr) == ce(errorline, "Attribute: 'a' did not receive a value for env Env('pp')") ok (ex.message) == "There were 1 errors when defining attribute 'a'"
def to_comparable_v(v2d): res = [] for subvec in v2d: if subvec != []: ok(isinstance(subvec[0], tuple)).is_truthy() tmp = tuple() for i in subvec: tmp = tmp + i res.append(tmp) res.sort() return res
def _g(self): try: with dummy.dummy_io('stdin not used') as d_io: with ConfigRoot(prod, [prod, pp]) as cr: errorline = lineno() + 1 cr.a(prod=1, pp="hello") fail ("Expected exception") except ConfigException as ex: sout, serr = d_io ok (serr) == ce(errorline, "Found different types of property 'a' for different envs: <type 'int'> previously found types: [<type 'str'>]") ok (ex.message) == "There were 1 errors when defining attribute 'a'"
def _d(self): try: with dummy.dummy_io('stdin not used') as d_io: dd1 = Env('dd') errorline = lineno() + 1 dd2 = EnvGroup('dd') fail ("Expected exception") except EnvException as ex: sout, serr = d_io ok (serr) == ce(errorline, "TODO") ok (ex.message) == "TODO"
def test_compile_simplest(self): sections = P(self.code_test_compile_simplest, {}) sections = list(sections) ok(len(sections)) == 1 sec1 = sections[0] ok(sec1.name) == "sec1" vals = sec1.vals ok(vals['wait_for_previous']).is_(None) ok(vals['iodepth']) == 1 ok(vals['some_extra'] - 1.2314) < 1E-7
def test_compile_defaults(self): sections = P(self.code_test_params_in_defaults, {}) sections = list(sections) ok(len(sections)) == 1 sec1 = sections[0] ok(sec1.name) == "sec1" vals = sec1.vals ok(vals['wait_for_previous']).is_(None) ok(vals['iodepth']) == 1 ok(vals['runtime']) == 20
def _a(self): @required_if('a', 'b, c') class root(ConfigRoot): pass with root(prod, [prod]) as cr: cr.a(prod=0) cr.b(prod=1) ok (cr.a) == 0 ok (cr.b) == 1
def _c2(self): try: with dummy.dummy_io('stdin not used') as d_io: cc21 = Env('cc21') cc22 = EnvGroup('cc22', cc21) errorline = lineno() + 1 cc22 = EnvGroup('cc22', cc22) fail ("Expected exception") except EnvException as ex: sout, serr = d_io ok (serr) == ce(errorline, "TODO") ok (ex.message) == "TODO"
def _i(self): try: with dummy.dummy_io('stdin not used') as d_io: ii1 = Env('ii1') ii2 = EnvGroup('ii2', ii1) errorline = lineno() + 1 ii3 = EnvGroup('ii3', ii2, ii1) fail ("Expected exception") except EnvException as ex: sout, serr = d_io ok (serr) == ce(errorline, "TODO") ok (ex.message) == "TODO"
def _b(self): try: with dummy.dummy_io('stdin not used') as d_io: bb1 = Env('bb') bb2 = EnvGroup('bb2', bb1) errorline = lineno() + 1 bb3 = EnvGroup('bb2', bb1) fail ("Expected exception") except EnvException as ex: sout, serr = d_io ok (serr) == ce(errorline, "TODO") ok (ex.message) == "TODO"
def test__set_cache_storage(self): if "default then Engine.cache is TextCacheStorage instance": ok (tenjin.Engine.cache).is_a(tenjin.TextCacheStorage) if "cache=True specified then use default cache object": engine = tenjin.Engine(cache=True) ok ('cache' in engine.__dict__) == False ok (engine.cache).is_(tenjin.Engine.cache) ok (engine.cache).is_(tenjin.Engine(cache=True).cache) if "cache=True and default cache is not set then create MarshalCacheStorage object for each engine": bkup = tenjin.Engine.cache try: tenjin.Engine.cache = None engine = tenjin.Engine(cache=True) ok (engine.__dict__).contains('cache') ok (engine.cache).is_a(tenjin.MarshalCacheStorage) not_ok (engine.cache).is_(tenjin.Engine(cache=True).cache) finally: tenjin.Engine.cache = bkup #if "cache=None specified then set MemoryCacheObject instance as cache object": # engine = tenjin.Engine(cache=None) # ok ('cache' in engine.__dict__) == True # ok (engine.cache).is_a(tenjin.MemoryCacheStorage) if "cache=None then do nothing": engine = tenjin.Engine(cache=None) not_ok (engine.__dict__).contains('cache') if "cache=False specified then don't use cache object": engine = tenjin.Engine(cache=False) ok (engine.__dict__).contains('cache') ok (engine.cache) == None if "CacheStorage instance is specified then use it as cache object": cache_storage = tenjin.MarshalCacheStorage() engine = tenjin.Engine(cache=cache_storage) ok (engine.__dict__).contains('cache') ok (engine.cache).is_(cache_storage) if "invalid object is specified as cache object then raise ValueError": def f(): tenjin.Engine(cache=123) ok (f).raises(ValueError, '123: invalid cache object.')
def test_preprocessor(self): data = EngineTest._testdata['test_preprocessor'] try: basenames = ('form', 'create', 'update', 'layout', ) filenames = [] for name in basenames: filename = 'prep_%s.pyhtml' % name filenames.append(filename) write_file(filename, data[name]) engine = tenjin.Engine(prefix='prep_', postfix='.pyhtml', layout=':layout', preprocess=True) # context = { 'title': 'Create', 'action': 'create', 'params': { 'state': 'NY' }, } actual = engine.render(':create', context) # 1st ok (actual) == data['expected1'] context['params'] = {'state': 'xx'} actual = engine.render(':create', context) # 2nd #ok (actual) == data['expected1'] expected = data['expected1'].replace(r' checked="checked"', '') ok (actual) == expected # context = { 'title': 'Update', 'action': 'update', 'params': { 'state': 'NY' }, } actual = engine.render(':update', context) # 1st ok (actual) == data['expected2'] context['params'] = { 'state': 'xx' } actual = engine.render(':update', context) # 2nd ok (actual) == data['expected2'] # not changed! # ok (engine.get_template(':form').script) == data['cache1'] ok (engine.get_template(':create').script) == data['cache2'] ok (engine.get_template(':layout').script) == data['cache3'] ok (engine.get_template(':update').script) == data['cache4'] # finally: _remove_files(filenames)
def _(self): e = tenjin.Engine(preprocess=True) ok (e.pp).is_a(list).length(1) ok (e.pp[0]).is_a(tenjin.TemplatePreprocessor)
def _(self): self.p.persons(self.id).put({"name": "Albert Einstein"}) result = self.p.persons(self.id).get() ok(result['result']['name']) == "Albert Einstein"
def test_cachename(self): engine = tenjin.Engine() if spec("return cache file path"): ok (engine.cachename('foo.pyhtml')) == 'foo.pyhtml.cache'
def test_to_filename(self): engine = tenjin.Engine(prefix='user_', postfix='.pyhtml') if spec("if template_name starts with ':', add prefix and postfix to it."): ok (engine.to_filename(':list')) == 'user_list.pyhtml' if spec("if template_name doesn't start with ':', just return it."): ok (engine.to_filename('list')) == 'list'
def test__create_template(self): e1 = tenjin.Engine(path=['_views/blog', '_views']) t = None if spec("if input is not specified then just create empty template object."): t = e1._create_template(None) ok (t).is_a(tenjin.Template) ok (t.filename) == None ok (t.script) == None if spec("if input is specified then create template object and return it."): t = e1._create_template('<p>#{_content}</p>', '_views/layout.pyhtml') ok (t).is_a(tenjin.Template) ok (t.filename) == "_views/layout.pyhtml" ok (t.script) == lvars + "_extend(('''<p>''', _to_str(_content), '''</p>''', ));"
def test_get_template(self): e1 = tenjin.Engine(path=['_views/blog', '_views'], postfix='.pyhtml') filepath = '_views/blog/index.pyhtml' fullpath = os.getcwd() + filepath cachepath = fullpath + '.cache' assert not os.path.exists(cachepath) t = None if spec("return template object.") and \ spec("accept template_name such as ':index'."): t = e1.get_template(':index') ok (t).is_a(tenjin.Template) ok (t.filename) == filepath if spec("if template object is added by add_template(), return it."): tmp = tenjin.Template('foo.pyhtml', input="<<dummy>>") e1.add_template(tmp) ok (e1.get_template('foo.pyhtml')).is_(tmp) if spec("get filepath and fullpath of template"): e1._filepaths['index.pyhtml'] == (filepath, fullpath) if spec("if template file is not found then raise TemplateNotFoundError"): def f(): e1.get_template('index') ok (f).raises(tenjin.TemplateNotFoundError, "index: filename not found (path=['_views/blog', '_views']).") if spec("use full path as base of cache file path") and \ spec("get template object from cache"): ok (list(e1.cache.items.keys())) == ["%s/_views/blog/index.pyhtml.cache" % os.getcwd()] if spec("change template filename according to prefer_fullpath"): pass if spec("use full path as base of cache file path"): pass if spec("get template object from cache"): pass if spec("if template object is not found in cache or is expired..."): e1.cache.clear() ok (len(e1.cache.items)) == 0 tname = ':layout' fpath = '_views/layout.pyhtml' cpath = os.path.join(os.getcwd(), '_views/layout.pyhtml.cache') not_ok (cpath).exists() if spec("create template object."): t = e1.get_template(tname) ok (t).is_a(tenjin.Template) if spec("set timestamp and filename of template object."): ok (t.timestamp) == os.path.getmtime(filepath) ok (t.filename) == fpath delta = JYTHON and 0.03 or 0.003 ok (t._last_checked_at).in_delta(time.time(), delta) if spec("save template object into cache."): ok (cpath).exists() ok (len(e1.cache.items)) == 1 ok (e1.cache.items).contains(cpath)
def _test(self): input = getattr(self, 'input', '') source = getattr(self, 'source', None) expected = getattr(self, 'expected', None) exception = getattr(self, 'exception', None) errormsg = getattr(self, 'errormsg', None) options = getattr(self, 'options', '') filename = getattr(self, 'filename', None) context_file = getattr(self, 'context_file', None) context_data = getattr(self, 'context_data', None) encoding = getattr(self, 'encoding', None) # if python_version < '2.5': if expected: expected = expected.replace(': unexpected indent', ': invalid syntax') # if JYTHON: if self._testMethodName == 'test_lint5': expected = ( ".test.pyhtml:5:4: mismatched input 'else' expecting DEDENT\n" " 5: else\n" " ^\n") # if PYPY: if errormsg: errormsg = _errmsg(errormsg) if self._testMethodName == 'test_lint5': expected = (".test.pyhtml:5:4: invalid syntax\n" " 5: else\n" " ^\n") # if filename is not False: if filename is None: filename = '.test.pyhtml' #write_file(filename, input) for fname, s in zip(to_list(filename), to_list(input)): if encoding and isinstance(s, _unicode): s = s.encode(encoding) write_file(fname, s) # if isinstance(options, list): argv = options elif isinstance(options, str): argv = [item for item in options.split(' ') if item] argv.insert(0, 'tenjin') if filename: #argv.append(filename) argv.extend(to_list(filename)) #print "*** debug: argv=%s" % repr(argv) # if context_file: s = context_data if encoding and instance(s, _unicode): s = s.encode(encoding) write_file(context_file, s) # try: app = Main(argv) if exception: lst = [None] def f1(): try: output = app.execute() except Exception: ex = sys.exc_info()[1] lst[0] = ex raise ex ok(f1).raises(exception) if errormsg: ex = lst[0] ok(str(ex)) == errormsg else: output = app.execute() #print "*** expected=%s" % expected #print "*** output=%s" % output if python2: if encoding and isinstance(output, unicode): output = output.encode(encoding) ok(output) == expected finally: try: if filename: #os.remove(filename) for fname in to_list(filename): os.unlink(fname) if context_file: os.remove(context_file) except: pass
def _(self): result = self.p.persons(self.id).get() data = result['result'] ok(data['name']) == "Albert Keinstein"
def _(self): result = self.p.persons(self.id).get() data = result['result'] ok(data['links'][0]['url']) == "http://www.wikipedia.com/AlbertEinstein" ok(data['links'][0]['note']) == "Wikipedia"
def f1(): engine = tenjin.Engine(cache=True) ok (engine.get_template('content.pyhtml').args) != None output = engine.render('content.pyhtml', context)
def _(self): result = self.p.persons(self.id).delete() ok(result) == True result = self.p.persons(self.id).delete() ok(result) == True
def _(self): e = tenjin.Engine(preprocess=True) ok (e.pp[0].factory) == tenjin.Preprocessor e = tenjin.Engine(preprocess=True, preprocessorclass=tenjin.SafePreprocessor) ok (e.pp[0].factory) == tenjin.SafePreprocessor
def _(self): result = self.p.persons(self.id).delete() ok(result) == True def f(): result = self.p.persons(self.id).get() ok (f).raises(HttpClientError)
def _test(expected, statement): content_html = hash['content_html'] + statement write_file(fname('content_html'), content_html) actual = engine.render(':content_html', context) ok (actual) == expected
def test_cachefile(self): data = EngineTest._testdata['test_cachefile'] filenames = { 'layout': 'layout.pyhtml', 'page': 'account_create.pyhtml', 'form': 'account_form.pyhtml', } expected = data['expected'] context = { 'params': { } } cache_filenames = ['account_create.pyhtml.cache', 'account_form.pyhtml.cache'] try: for key, filename in filenames.items(): write_file(filename, data[key]) props = { 'prefix':'account_', 'postfix':'.pyhtml', 'layout':'layout.pyhtml' } ## no caching props['cache'] = False engine = tenjin.Engine(**props) output = engine.render(':create', context) ok (output) == expected for fname in cache_filenames: not_ok (fname).exists() ## marshal caching if not JYTHON: props['cache'] = tenjin.MarshalCacheStorage() engine = tenjin.Engine(**props) output = engine.render(':create', context) ok (output) == expected if python2: nullbyte = '\0' elif python3: nullbyte = '\0'.encode('ascii') for fname in cache_filenames: ok (fname).exists() # file created? s = read_file(fname, 'rb') # read binary file ok (s.find(nullbyte)) >= 0 # binary file? f = open(fname, 'rb') fn = lambda: marshal.load(f) try: ok (fn).not_raise() # marshal? finally: f.close() engine = tenjin.Engine(**props) output = engine.render(':create', context) ok (output) == expected # reloadable? # for fname in glob('*.pyhtml.cache'): os.unlink(fname) for fname in cache_filenames: not_ok (fname).exists() ## pickle caching props['cache'] = tenjin.PickleCacheStorage() engine = tenjin.Engine(**props) output = engine.render(':create', context) ok (output) == expected if python2: nullbyte = '\0' elif python3: nullbyte = '\0'.encode('ascii') for fname in cache_filenames: ok (fname).exists() # file created? s = read_file(fname, 'rb') # read text file if python2: ok (s.find(nullbyte)) < 0 # text file? (pickle protocol ver 2) elif python3: ok (s.find(nullbyte)) >= 0 # binary file? (pickle protocol ver 3) f = open(fname, 'rb') fn = lambda: Pickle.load(f) try: ok (fn).not_raise(ValueError) finally: f.close() f = open(fname, 'rb') pickle.load(f) f.close() engine = tenjin.Engine(**props) output = engine.render(':create', context) ok (output) == expected # reloadable? # for fname in glob('*.cache'): os.unlink(fname) for fname in cache_filenames: not_ok (fname).exists() ## text caching props['cache'] = tenjin.TextCacheStorage() engine = tenjin.Engine(**props) output = engine.render(':create', context) ok (output) == expected if python2: nullchar = '\0' elif python3: nullchar = '\0' for fname in cache_filenames: ok (fname).exists() # file created? s = read_file(fname, 'r') # read text file ok (s.find(nullchar)) < 0 # text file? if JYTHON: continue #fn = lambda: marshal.loads(s) f = open(fname, 'rb') fn = lambda: marshal.load(f) try: if python3: ok (fn).raises(ValueError) # non-marshal? if sys.version_info[1] == 0: # python 3.0 ok (str(fn.exception)) == "bad marshal data" else: # python 3.1 or later ok (str(fn.exception)) == "bad marshal data (unknown type code)" elif python2 and sys.version_info[1] >= 5: ok (fn).raises(EOFError, "EOF read where object expected") # non-marshal? finally: f.close() engine = tenjin.Engine(**props) output = engine.render(':create', context) ok (output) == expected # reloadable? finally: _remove_files(filenames.values())