How to use Foo method in chai

Best JavaScript code snippet using chai

test_alias.py

Source:test_alias.py Github

copy

Full Screen

...75 def test_init_args(self):76 class ClassicFoo:77 def __init__(self, foo, bar):78 pass79 class NewFoo(object):80 def __init__(self, foo, bar):81 pass82 self.assertRaises(TypeError, ClassAlias, ClassicFoo)83 ClassAlias(NewFoo)84 def test_createInstance(self):85 x = ClassAlias(Spam, 'org.example.spam.Spam')86 y = x.createInstance()87 self.assertTrue(isinstance(y, Spam))88 def test_str(self):89 class Eggs(object):90 pass91 x = ClassAlias(Eggs, 'org.example.eggs.Eggs')92 self.assertEqual(str(x), 'org.example.eggs.Eggs')93 def test_eq(self):94 class A(object):95 pass96 class B(object):97 pass98 x = ClassAlias(A, 'org.example.A')99 y = ClassAlias(A, 'org.example.A')100 z = ClassAlias(B, 'org.example.B')101 self.assertEqual(x, A)102 self.assertEqual(x, y)103 self.assertNotEquals(x, z)104class GetEncodableAttributesTestCase(unittest.TestCase):105 """106 Tests for L{ClassAlias.getEncodableAttributes}107 """108 def setUp(self):109 self.alias = ClassAlias(Spam, 'foo', defer=True)110 self.obj = Spam()111 def test_empty(self):112 attrs = self.alias.getEncodableAttributes(self.obj)113 self.assertEqual(attrs, {})114 def test_static(self):115 self.alias.static_attrs = ['foo', 'bar']116 self.alias.compile()117 self.obj.foo = 'bar'118 # leave self.obj.bar119 self.assertFalse(hasattr(self.obj, 'bar'))120 attrs = self.alias.getEncodableAttributes(self.obj)121 self.assertEqual(attrs, {'foo': 'bar', 'bar': pyamf.Undefined})122 def test_not_dynamic(self):123 self.alias.compile()124 self.alias.dynamic = False125 self.assertEqual(self.alias.getEncodableAttributes(self.obj), {})126 def test_dynamic(self):127 self.alias.compile()128 self.assertEqual(self.alias.encodable_properties, None)129 self.obj.foo = 'bar'130 self.obj.bar = 'foo'131 attrs = self.alias.getEncodableAttributes(self.obj)132 self.assertEqual(attrs, {'foo': 'bar', 'bar': 'foo'})133 def test_proxy(self):134 from pyamf import flex135 c = pyamf.get_encoder(pyamf.AMF3)136 self.alias.proxy_attrs = ('foo', 'bar')137 self.alias.compile()138 self.assertEqual(self.alias.proxy_attrs, ['bar', 'foo'])139 self.obj.foo = ['bar', 'baz']140 self.obj.bar = {'foo': 'gak'}141 attrs = self.alias.getEncodableAttributes(self.obj, c)142 k = attrs.keys()143 k.sort()144 self.assertEqual(k, ['bar', 'foo'])145 self.assertTrue(isinstance(attrs['foo'], flex.ArrayCollection))146 self.assertEqual(attrs['foo'], ['bar', 'baz'])147 self.assertTrue(isinstance(attrs['bar'], flex.ObjectProxy))148 self.assertEqual(attrs['bar']._amf_object, {'foo': 'gak'})149 def test_synonym(self):150 self.alias.synonym_attrs = {'foo': 'bar'}151 self.alias.compile()152 self.assertFalse(self.alias.shortcut_encode)153 self.assertFalse(self.alias.shortcut_decode)154 self.obj.foo = 'bar'155 self.obj.spam = 'eggs'156 ret = self.alias.getEncodableAttributes(self.obj)157 self.assertEquals(ret, {'bar': 'bar', 'spam': 'eggs'})158class GetDecodableAttributesTestCase(unittest.TestCase):159 """160 Tests for L{ClassAlias.getDecodableAttributes}161 """162 def setUp(self):163 self.alias = ClassAlias(Spam, 'foo', defer=True)164 self.obj = Spam()165 def test_compile(self):166 self.assertFalse(self.alias._compiled)167 self.alias.applyAttributes(self.obj, {})168 self.assertTrue(self.alias._compiled)169 def test_missing_static_property(self):170 self.alias.static_attrs = ['foo', 'bar']171 self.alias.compile()172 attrs = {'foo': None} # missing bar key ..173 self.assertRaises(AttributeError, self.alias.getDecodableAttributes,174 self.obj, attrs)175 def test_no_static(self):176 self.alias.compile()177 attrs = {'foo': None, 'bar': [1, 2, 3]}178 ret = self.alias.getDecodableAttributes(self.obj, attrs)179 self.assertEqual(ret, {'foo': None, 'bar': [1, 2, 3]})180 def test_readonly(self):181 self.alias.compile()182 self.alias.readonly_attrs = ['bar']183 attrs = {'foo': None, 'bar': [1, 2, 3]}184 ret = self.alias.getDecodableAttributes(self.obj, attrs)185 self.assertEqual(ret, {'foo': None})186 def test_not_dynamic(self):187 self.alias.compile()188 self.alias.decodable_properties = set(['bar'])189 self.alias.dynamic = False190 attrs = {'foo': None, 'bar': [1, 2, 3]}191 ret = self.alias.getDecodableAttributes(self.obj, attrs)192 self.assertEqual(ret, {'bar': [1, 2, 3]})193 def test_dynamic(self):194 self.alias.compile()195 self.alias.static_properties = ['bar']196 self.alias.dynamic = True197 attrs = {'foo': None, 'bar': [1, 2, 3]}198 ret = self.alias.getDecodableAttributes(self.obj, attrs)199 self.assertEqual(ret, {'foo': None, 'bar': [1, 2, 3]})200 def test_complex(self):201 self.alias.compile()202 self.alias.static_properties = ['foo', 'bar']203 self.alias.exclude_attrs = ['baz', 'gak']204 self.alias.readonly_attrs = ['spam', 'eggs']205 attrs = {206 'foo': 'foo',207 'bar': 'bar',208 'baz': 'baz',209 'gak': 'gak',210 'spam': 'spam',211 'eggs': 'eggs',212 'dyn1': 'dyn1',213 'dyn2': 'dyn2'214 }215 ret = self.alias.getDecodableAttributes(self.obj, attrs)216 self.assertEquals(ret, {217 'foo': 'foo',218 'bar': 'bar',219 'dyn2': 'dyn2',220 'dyn1': 'dyn1'221 })222 def test_complex_not_dynamic(self):223 self.alias.compile()224 self.alias.decodable_properties = ['foo', 'bar']225 self.alias.exclude_attrs = ['baz', 'gak']226 self.alias.readonly_attrs = ['spam', 'eggs']227 self.alias.dynamic = False228 attrs = {229 'foo': 'foo',230 'bar': 'bar',231 'baz': 'baz',232 'gak': 'gak',233 'spam': 'spam',234 'eggs': 'eggs',235 'dyn1': 'dyn1',236 'dyn2': 'dyn2'237 }238 ret = self.alias.getDecodableAttributes(self.obj, attrs)239 self.assertEqual(ret, {'foo': 'foo', 'bar': 'bar'})240 def test_static(self):241 self.alias.dynamic = False242 self.alias.compile()243 self.alias.decodable_properties = set(['foo', 'bar'])244 attrs = {245 'foo': 'foo',246 'bar': 'bar',247 'baz': 'baz',248 'gak': 'gak',249 }250 ret = self.alias.getDecodableAttributes(self.obj, attrs)251 self.assertEqual(ret, {'foo': 'foo', 'bar': 'bar'})252 def test_proxy(self):253 from pyamf import flex254 c = pyamf.get_encoder(pyamf.AMF3)255 self.alias.proxy_attrs = ('foo', 'bar')256 self.alias.compile()257 self.assertEqual(self.alias.proxy_attrs, ['bar', 'foo'])258 attrs = {259 'foo': flex.ArrayCollection(['bar', 'baz']),260 'bar': flex.ObjectProxy({'foo': 'gak'})261 }262 ret = self.alias.getDecodableAttributes(self.obj, attrs, c)263 self.assertEqual(ret, {264 'foo': ['bar', 'baz'],265 'bar': {'foo': 'gak'}266 })267 def test_synonym(self):268 self.alias.synonym_attrs = {'foo': 'bar'}269 self.alias.compile()270 self.assertFalse(self.alias.shortcut_encode)271 self.assertFalse(self.alias.shortcut_decode)272 attrs = {273 'foo': 'foo',274 'spam': 'eggs'275 }276 ret = self.alias.getDecodableAttributes(self.obj, attrs)277 self.assertEquals(ret, {'bar': 'foo', 'spam': 'eggs'})278class ApplyAttributesTestCase(unittest.TestCase):279 """280 Tests for L{ClassAlias.applyAttributes}281 """282 def setUp(self):283 self.alias = ClassAlias(Spam, 'foo', defer=True)284 self.obj = Spam()285 def test_object(self):286 class Foo(object):287 pass288 attrs = {'foo': 'spam', 'bar': 'eggs'}289 self.obj = Foo()290 self.alias = ClassAlias(Foo, 'foo', defer=True)291 self.assertEqual(self.obj.__dict__, {})292 self.alias.applyAttributes(self.obj, attrs)293 self.assertEqual(self.obj.__dict__, {'foo': 'spam', 'bar': 'eggs'})294 def test_classic(self):295 class Foo:296 pass297 attrs = {'foo': 'spam', 'bar': 'eggs'}298 self.obj = Foo()299 self.alias = ClassAlias(Foo, 'foo', defer=True)300 self.assertEqual(self.obj.__dict__, {})301 self.alias.applyAttributes(self.obj, attrs)302 self.assertEqual(self.obj.__dict__, {'foo': 'spam', 'bar': 'eggs'})303 def test_readonly(self):304 self.alias.readonly_attrs = ['foo', 'bar']305 attrs = {'foo': 'spam', 'bar': 'eggs'}306 self.assertEqual(self.obj.__dict__, {})307 self.alias.applyAttributes(self.obj, attrs)308 self.assertEqual(self.obj.__dict__, {})309 def test_exclude(self):310 self.alias.exclude_attrs = ['foo', 'bar']311 attrs = {'foo': 'spam', 'bar': 'eggs'}312 self.assertEqual(self.obj.__dict__, {})...

Full Screen

Full Screen

test_auth.py

Source:test_auth.py Github

copy

Full Screen

1import py2from py.path import SvnAuth3import svntestbase4from threading import Thread5import time6from py.__.misc.killproc import killproc7from py.__.conftest import option8def make_repo_auth(repo, userdata):9 """ write config to repo10 11 user information in userdata is used for auth12 userdata has user names as keys, and a tuple (password, readwrite) as13 values, where 'readwrite' is either 'r' or 'rw'14 """15 confdir = py.path.local(repo).join('conf')16 confdir.join('svnserve.conf').write('''\17[general]18anon-access = none19password-db = passwd20authz-db = authz21realm = TestRepo22''')23 authzdata = '[/]\n'24 passwddata = '[users]\n'25 for user in userdata:26 authzdata += '%s = %s\n' % (user, userdata[user][1])27 passwddata += '%s = %s\n' % (user, userdata[user][0])28 confdir.join('authz').write(authzdata)29 confdir.join('passwd').write(passwddata)30def serve_bg(repopath):31 pidfile = py.path.local(repopath).join('pid')32 port = 1000033 e = None34 while port < 10010:35 cmd = 'svnserve -d -T --listen-port=%d --pid-file=%s -r %s' % (36 port, pidfile, repopath)37 try:38 py.process.cmdexec(cmd)39 except py.process.cmdexec.Error, e:40 pass41 else:42 # XXX we assume here that the pid file gets written somewhere, I43 # guess this should be relatively safe... (I hope, at least?)44 while True:45 pid = pidfile.read()46 if pid:47 break48 # needs a bit more time to boot49 time.sleep(0.1)50 return port, int(pid)51 port += 152 raise IOError('could not start svnserve: %s' % (e,))53class TestSvnAuth(object):54 def test_basic(self):55 auth = py.path.SvnAuth('foo', 'bar')56 assert auth.username == 'foo'57 assert auth.password == 'bar'58 assert str(auth)59 def test_makecmdoptions_uname_pw_makestr(self):60 auth = py.path.SvnAuth('foo', 'bar')61 assert auth.makecmdoptions() == '--username="foo" --password="bar"'62 def test_makecmdoptions_quote_escape(self):63 auth = py.path.SvnAuth('fo"o', '"ba\'r"')64 assert auth.makecmdoptions() == '--username="fo\\"o" --password="\\"ba\'r\\""'65 def test_makecmdoptions_no_cache_auth(self):66 auth = py.path.SvnAuth('foo', 'bar', cache_auth=False)67 assert auth.makecmdoptions() == ('--username="foo" --password="bar" '68 '--no-auth-cache')69 def test_makecmdoptions_no_interactive(self):70 auth = py.path.SvnAuth('foo', 'bar', interactive=False)71 assert auth.makecmdoptions() == ('--username="foo" --password="bar" '72 '--non-interactive')73 def test_makecmdoptions_no_interactive_no_cache_auth(self):74 auth = py.path.SvnAuth('foo', 'bar', cache_auth=False,75 interactive=False)76 assert auth.makecmdoptions() == ('--username="foo" --password="bar" '77 '--no-auth-cache --non-interactive')78class svnwc_no_svn(py.path.svnwc):79 def __init__(self, *args, **kwargs):80 self.commands = []81 super(svnwc_no_svn, self).__init__(*args, **kwargs)82 def _svn(self, *args):83 self.commands.append(args)84class TestSvnWCAuth(object):85 def setup_method(self, meth):86 self.auth = SvnAuth('user', 'pass', cache_auth=False)87 def test_checkout(self):88 wc = svnwc_no_svn('foo', auth=self.auth)89 wc.checkout('url')90 assert wc.commands[0][-1] == ('--username="user" --password="pass" '91 '--no-auth-cache')92 def test_commit(self):93 wc = svnwc_no_svn('foo', auth=self.auth)94 wc.commit('msg')95 assert wc.commands[0][-1] == ('--username="user" --password="pass" '96 '--no-auth-cache')97 def test_checkout_no_cache_auth(self):98 wc = svnwc_no_svn('foo', auth=self.auth)99 wc.checkout('url')100 assert wc.commands[0][-1] == ('--username="user" --password="pass" '101 '--no-auth-cache')102 def test_checkout_auth_from_constructor(self):103 wc = svnwc_no_svn('foo', auth=self.auth)104 wc.checkout('url')105 assert wc.commands[0][-1] == ('--username="user" --password="pass" '106 '--no-auth-cache')107class svnurl_no_svn(py.path.svnurl):108 cmdexec_output = 'test'109 popen_output = 'test'110 def _cmdexec(self, cmd):111 self.commands.append(cmd)112 return self.cmdexec_output113 def _popen(self, cmd):114 self.commands.append(cmd)115 return self.popen_output116class TestSvnURLAuth(object):117 def setup_method(self, meth):118 svnurl_no_svn.commands = []119 self.auth = SvnAuth('foo', 'bar')120 def test_init(self):121 u = svnurl_no_svn('http://foo.bar/svn')122 assert u.auth is None123 u = svnurl_no_svn('http://foo.bar/svn', auth=self.auth)124 assert u.auth is self.auth125 def test_new(self):126 u = svnurl_no_svn('http://foo.bar/svn/foo', auth=self.auth)127 new = u.new(basename='bar')128 assert new.auth is self.auth129 assert new.url == 'http://foo.bar/svn/bar'130 def test_join(self):131 u = svnurl_no_svn('http://foo.bar/svn', auth=self.auth)132 new = u.join('foo')133 assert new.auth is self.auth134 assert new.url == 'http://foo.bar/svn/foo'135 def test_listdir(self):136 u = svnurl_no_svn('http://foo.bar/svn', auth=self.auth)137 u.cmdexec_output = '''\138 1717 johnny 1529 Nov 04 14:32 LICENSE.txt139 1716 johnny 5352 Nov 04 14:28 README.txt140'''141 paths = u.listdir()142 assert paths[0].auth is self.auth143 assert paths[1].auth is self.auth144 assert paths[0].basename == 'LICENSE.txt'145 def test_info(self):146 u = svnurl_no_svn('http://foo.bar/svn/LICENSE.txt', auth=self.auth)147 def dirpath(self):148 return self149 u.cmdexec_output = '''\150 1717 johnny 1529 Nov 04 14:32 LICENSE.txt151 1716 johnny 5352 Nov 04 14:28 README.txt152'''153 org_dp = u.__class__.dirpath154 u.__class__.dirpath = dirpath155 try:156 info = u.info()157 finally:158 u.dirpath = org_dp159 assert info.size == 1529160 def test_open(self):161 u = svnurl_no_svn('http://foo.bar/svn', auth=self.auth)162 foo = u.join('foo')163 foo.check = lambda *args, **kwargs: True164 ret = foo.open()165 assert ret == 'test'166 assert '--username="foo" --password="bar"' in foo.commands[0]167 def test_dirpath(self):168 u = svnurl_no_svn('http://foo.bar/svn/foo', auth=self.auth)169 parent = u.dirpath()170 assert parent.auth is self.auth171 def test_mkdir(self):172 u = svnurl_no_svn('http://foo.bar/svn', auth=self.auth)173 u.mkdir('foo', msg='created dir foo')174 assert '--username="foo" --password="bar"' in u.commands[0]175 def test_copy(self):176 u = svnurl_no_svn('http://foo.bar/svn', auth=self.auth)177 u2 = svnurl_no_svn('http://foo.bar/svn2')178 u.copy(u2, 'copied dir')179 assert '--username="foo" --password="bar"' in u.commands[0]180 def test_rename(self):181 u = svnurl_no_svn('http://foo.bar/svn/foo', auth=self.auth)182 u.rename('http://foo.bar/svn/bar', 'moved foo to bar')183 assert '--username="foo" --password="bar"' in u.commands[0]184 def test_remove(self):185 u = svnurl_no_svn('http://foo.bar/svn/foo', auth=self.auth)186 u.remove(msg='removing foo')187 assert '--username="foo" --password="bar"' in u.commands[0]188 def test_export(self):189 u = svnurl_no_svn('http://foo.bar/svn', auth=self.auth)190 target = py.path.local('/foo')191 u.export(target)192 assert '--username="foo" --password="bar"' in u.commands[0]193 def test_log(self):194 u = svnurl_no_svn('http://foo.bar/svn/foo', auth=self.auth)195 u.popen_output = py.std.StringIO.StringIO('''\196<?xml version="1.0"?>197<log>198<logentry revision="51381">199<author>guido</author>200<date>2008-02-11T12:12:18.476481Z</date>201<msg>Creating branch to work on auth support for py.path.svn*.202</msg>203</logentry>204</log>205''')206 u.check = lambda *args, **kwargs: True207 ret = u.log(10, 20, verbose=True)208 assert '--username="foo" --password="bar"' in u.commands[0]209 assert len(ret) == 1210 assert int(ret[0].rev) == 51381211 assert ret[0].author == 'guido'212 def test_propget(self):213 u = svnurl_no_svn('http://foo.bar/svn', auth=self.auth)214 u.propget('foo')215 assert '--username="foo" --password="bar"' in u.commands[0]216class SvnAuthFunctionalTestBase(object):217 def setup_class(cls):218 if not option.runslowtests:219 py.test.skip('skipping slow functional tests - use --runslowtests '220 'to override')221 def setup_method(self, meth):222 func_name = meth.im_func.func_name223 self.repo = svntestbase.make_test_repo('TestSvnAuthFunctional.%s' % (224 func_name,))225 repodir = str(self.repo)[7:]226 if py.std.sys.platform == 'win32':227 # remove trailing slash...228 repodir = repodir[1:]229 self.repopath = py.path.local(repodir)230 self.temppath = py.test.ensuretemp('TestSvnAuthFunctional.%s' % (231 func_name))232 self.auth = py.path.SvnAuth('johnny', 'foo', cache_auth=False,233 interactive=False)234 def _start_svnserve(self):235 make_repo_auth(self.repopath, {'johnny': ('foo', 'rw')})236 try:237 return serve_bg(self.repopath.dirpath())238 except IOError, e:239 py.test.skip(str(e))240class TestSvnWCAuthFunctional(SvnAuthFunctionalTestBase):241 def test_checkout_constructor_arg(self):242 port, pid = self._start_svnserve()243 try:244 wc = py.path.svnwc(self.temppath, auth=self.auth)245 wc.checkout(246 'svn://localhost:%s/%s' % (port, self.repopath.basename))247 assert wc.join('.svn').check()248 finally:249 # XXX can we do this in a teardown_method too? not sure if that's250 # guaranteed to get called...251 killproc(pid)252 def test_checkout_function_arg(self):253 port, pid = self._start_svnserve()254 try:255 wc = py.path.svnwc(self.temppath, auth=self.auth)256 wc.checkout(257 'svn://localhost:%s/%s' % (port, self.repopath.basename))258 assert wc.join('.svn').check()259 finally:260 killproc(pid)261 def test_checkout_failing_non_interactive(self):262 port, pid = self._start_svnserve()263 try:264 auth = py.path.SvnAuth('johnny', 'bar', cache_auth=False,265 interactive=False)266 wc = py.path.svnwc(self.temppath, auth)267 py.test.raises(Exception,268 ("wc.checkout('svn://localhost:%s/%s' % "269 "(port, self.repopath.basename))"))270 finally:271 killproc(pid)272 def test_log(self):273 port, pid = self._start_svnserve()274 try:275 wc = py.path.svnwc(self.temppath, self.auth)276 wc.checkout(277 'svn://localhost:%s/%s' % (port, self.repopath.basename))278 foo = wc.ensure('foo.txt')279 wc.commit('added foo.txt')280 log = foo.log()281 assert len(log) == 1282 assert log[0].msg == 'added foo.txt'283 finally:284 killproc(pid)285 def test_switch(self):286 port, pid = self._start_svnserve()287 try:288 wc = py.path.svnwc(self.temppath, auth=self.auth)289 svnurl = 'svn://localhost:%s/%s' % (port, self.repopath.basename)290 wc.checkout(svnurl)291 wc.ensure('foo', dir=True).ensure('foo.txt').write('foo')292 wc.commit('added foo dir with foo.txt file')293 wc.ensure('bar', dir=True)294 wc.commit('added bar dir')295 bar = wc.join('bar')296 bar.switch(svnurl + '/foo')297 assert bar.join('foo.txt')298 finally:299 killproc(pid)300 def test_update(self):301 port, pid = self._start_svnserve()302 try:303 wc1 = py.path.svnwc(self.temppath.ensure('wc1', dir=True),304 auth=self.auth)305 wc2 = py.path.svnwc(self.temppath.ensure('wc2', dir=True),306 auth=self.auth)307 wc1.checkout(308 'svn://localhost:%s/%s' % (port, self.repopath.basename))309 wc2.checkout(310 'svn://localhost:%s/%s' % (port, self.repopath.basename))311 wc1.ensure('foo', dir=True)312 wc1.commit('added foo dir')313 wc2.update()314 assert wc2.join('foo').check()315 auth = py.path.SvnAuth('unknown', 'unknown', interactive=False)316 wc2.auth = auth317 py.test.raises(Exception, 'wc2.update()')318 finally:319 killproc(pid)320 def test_lock_unlock_status(self):321 port, pid = self._start_svnserve()322 try:323 wc = py.path.svnwc(self.temppath, auth=self.auth)324 wc.checkout(325 'svn://localhost:%s/%s' % (port, self.repopath.basename,))326 wc.ensure('foo', file=True)327 wc.commit('added foo file')328 foo = wc.join('foo')329 foo.lock()330 status = foo.status()331 assert status.locked332 foo.unlock()333 status = foo.status()334 assert not status.locked335 auth = py.path.SvnAuth('unknown', 'unknown', interactive=False)336 foo.auth = auth337 py.test.raises(Exception, 'foo.lock()')338 py.test.raises(Exception, 'foo.unlock()')339 finally:340 killproc(pid)341 def test_diff(self):342 port, pid = self._start_svnserve()343 try:344 wc = py.path.svnwc(self.temppath, auth=self.auth)345 wc.checkout(346 'svn://localhost:%s/%s' % (port, self.repopath.basename,))347 wc.ensure('foo', file=True)348 wc.commit('added foo file')349 wc.update()350 rev = int(wc.status().rev)351 foo = wc.join('foo')352 foo.write('bar')353 diff = foo.diff()354 assert '\n+bar\n' in diff355 foo.commit('added some content')356 diff = foo.diff()357 assert not diff358 diff = foo.diff(rev=rev)359 assert '\n+bar\n' in diff360 auth = py.path.SvnAuth('unknown', 'unknown', interactive=False)361 foo.auth = auth362 py.test.raises(Exception, 'foo.diff(rev=rev)')363 finally:364 killproc(pid)365class TestSvnURLAuthFunctional(SvnAuthFunctionalTestBase):366 def test_listdir(self):367 port, pid = self._start_svnserve()368 try:369 u = py.path.svnurl(370 'svn://localhost:%s/%s' % (port, self.repopath.basename),371 auth=self.auth)372 u.ensure('foo')373 paths = u.listdir()374 assert len(paths) == 1375 assert paths[0].auth is self.auth376 auth = SvnAuth('foo', 'bar', interactive=False)377 u = py.path.svnurl(378 'svn://localhost:%s/%s' % (port, self.repopath.basename),379 auth=auth)380 py.test.raises(Exception, 'u.listdir()')381 finally:382 killproc(pid)383 def test_copy(self):384 port, pid = self._start_svnserve()385 try:386 u = py.path.svnurl(387 'svn://localhost:%s/%s' % (port, self.repopath.basename),388 auth=self.auth)389 foo = u.ensure('foo')390 bar = u.join('bar')391 foo.copy(bar)392 assert bar.check()393 assert bar.auth is self.auth394 auth = SvnAuth('foo', 'bar', interactive=False)395 u = py.path.svnurl(396 'svn://localhost:%s/%s' % (port, self.repopath.basename),397 auth=auth)398 foo = u.join('foo')399 bar = u.join('bar')400 py.test.raises(Exception, 'foo.copy(bar)')401 finally:402 killproc(pid)403 def test_write_read(self):404 port, pid = self._start_svnserve()405 try:406 u = py.path.svnurl(407 'svn://localhost:%s/%s' % (port, self.repopath.basename),408 auth=self.auth)409 foo = u.ensure('foo')410 fp = foo.open()411 try:412 data = fp.read()413 finally:414 fp.close()415 assert data == ''416 auth = SvnAuth('foo', 'bar', interactive=False)417 u = py.path.svnurl(418 'svn://localhost:%s/%s' % (port, self.repopath.basename),419 auth=auth)420 foo = u.join('foo')421 py.test.raises(Exception, 'foo.open()')422 finally:423 killproc(pid)...

Full Screen

Full Screen

lint-format-strings.py

Source:lint-format-strings.py Github

copy

Full Screen

1#!/usr/bin/env python32#3# Copyright (c) 2018-2019 The Bitcoin Core developers4# Distributed under the MIT software license, see the accompanying5# file COPYING or http://www.opensource.org/licenses/mit-license.php.6#7# Lint format strings: This program checks that the number of arguments passed8# to a variadic format string function matches the number of format specifiers9# in the format string.10import argparse11import re12import sys13FALSE_POSITIVES = [14 ("src/dbwrapper.cpp", "vsnprintf(p, limit - p, format, backup_ap)"),15 ("src/index/base.cpp", "FatalError(const char* fmt, const Args&... args)"),16 ("src/netbase.cpp", "LogConnectFailure(bool manual_connection, const char* fmt, const Args&... args)"),17 ("src/util/system.cpp", "strprintf(_(COPYRIGHT_HOLDERS).translated, COPYRIGHT_HOLDERS_SUBSTITUTION)"),18 ("src/validationinterface.cpp", "LogPrint(BCLog::VALIDATION, fmt \"\\n\", __VA_ARGS__)"),19 ("src/wallet/wallet.h", "WalletLogPrintf(std::string fmt, Params... parameters)"),20 ("src/wallet/wallet.h", "LogPrintf((\"%s \" + fmt).c_str(), GetDisplayName(), parameters...)"),21 ("src/wallet/scriptpubkeyman.h", "WalletLogPrintf(std::string fmt, Params... parameters)"),22 ("src/wallet/scriptpubkeyman.h", "LogPrintf((\"%s \" + fmt).c_str(), m_storage.GetDisplayName(), parameters...)"),23 ("src/logging.h", "LogPrintf(const char* fmt, const Args&... args)"),24 ("src/wallet/scriptpubkeyman.h", "WalletLogPrintf(const std::string& fmt, const Params&... parameters)"),25]26def parse_function_calls(function_name, source_code):27 """Return an array with all calls to function function_name in string source_code.28 Preprocessor directives and C++ style comments ("//") in source_code are removed.29 >>> len(parse_function_calls("foo", "foo();bar();foo();bar();"))30 231 >>> parse_function_calls("foo", "foo(1);bar(1);foo(2);bar(2);")[0].startswith("foo(1);")32 True33 >>> parse_function_calls("foo", "foo(1);bar(1);foo(2);bar(2);")[1].startswith("foo(2);")34 True35 >>> len(parse_function_calls("foo", "foo();bar();// foo();bar();"))36 137 >>> len(parse_function_calls("foo", "#define FOO foo();"))38 039 """40 assert type(function_name) is str and type(source_code) is str and function_name41 lines = [re.sub("// .*", " ", line).strip()42 for line in source_code.split("\n")43 if not line.strip().startswith("#")]44 return re.findall(r"[^a-zA-Z_](?=({}\(.*).*)".format(function_name), " " + " ".join(lines))45def normalize(s):46 """Return a normalized version of string s with newlines, tabs and C style comments ("/* ... */")47 replaced with spaces. Multiple spaces are replaced with a single space.48 >>> normalize(" /* nothing */ foo\tfoo /* bar */ foo ")49 'foo foo foo'50 """51 assert type(s) is str52 s = s.replace("\n", " ")53 s = s.replace("\t", " ")54 s = re.sub(r"/\*.*?\*/", " ", s)55 s = re.sub(" {2,}", " ", s)56 return s.strip()57ESCAPE_MAP = {58 r"\n": "[escaped-newline]",59 r"\t": "[escaped-tab]",60 r'\"': "[escaped-quote]",61}62def escape(s):63 """Return the escaped version of string s with "\\\"", "\\n" and "\\t" escaped as64 "[escaped-backslash]", "[escaped-newline]" and "[escaped-tab]".65 >>> unescape(escape("foo")) == "foo"66 True67 >>> escape(r'foo \\t foo \\n foo \\\\ foo \\ foo \\"bar\\"')68 'foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]'69 """70 assert type(s) is str71 for raw_value, escaped_value in ESCAPE_MAP.items():72 s = s.replace(raw_value, escaped_value)73 return s74def unescape(s):75 """Return the unescaped version of escaped string s.76 Reverses the replacements made in function escape(s).77 >>> unescape(escape("bar"))78 'bar'79 >>> unescape("foo [escaped-tab] foo [escaped-newline] foo \\\\\\\\ foo \\\\ foo [escaped-quote]bar[escaped-quote]")80 'foo \\\\t foo \\\\n foo \\\\\\\\ foo \\\\ foo \\\\"bar\\\\"'81 """82 assert type(s) is str83 for raw_value, escaped_value in ESCAPE_MAP.items():84 s = s.replace(escaped_value, raw_value)85 return s86def parse_function_call_and_arguments(function_name, function_call):87 """Split string function_call into an array of strings consisting of:88 * the string function_call followed by "("89 * the function call argument #190 * ...91 * the function call argument #n92 * a trailing ");"93 The strings returned are in escaped form. See escape(...).94 >>> parse_function_call_and_arguments("foo", 'foo("%s", "foo");')95 ['foo(', '"%s",', ' "foo"', ')']96 >>> parse_function_call_and_arguments("foo", 'foo("%s", "foo");')97 ['foo(', '"%s",', ' "foo"', ')']98 >>> parse_function_call_and_arguments("foo", 'foo("%s %s", "foo", "bar");')99 ['foo(', '"%s %s",', ' "foo",', ' "bar"', ')']100 >>> parse_function_call_and_arguments("fooprintf", 'fooprintf("%050d", i);')101 ['fooprintf(', '"%050d",', ' i', ')']102 >>> parse_function_call_and_arguments("foo", 'foo(bar(foobar(barfoo("foo"))), foobar); barfoo')103 ['foo(', 'bar(foobar(barfoo("foo"))),', ' foobar', ')']104 >>> parse_function_call_and_arguments("foo", "foo()")105 ['foo(', '', ')']106 >>> parse_function_call_and_arguments("foo", "foo(123)")107 ['foo(', '123', ')']108 >>> parse_function_call_and_arguments("foo", 'foo("foo")')109 ['foo(', '"foo"', ')']110 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().to_bytes(buf), err);')111 ['strprintf(', '"%s (%d)",', ' std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>,wchar_t>().to_bytes(buf),', ' err', ')']112 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo<wchar_t>().to_bytes(buf), err);')113 ['strprintf(', '"%s (%d)",', ' foo<wchar_t>().to_bytes(buf),', ' err', ')']114 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo().to_bytes(buf), err);')115 ['strprintf(', '"%s (%d)",', ' foo().to_bytes(buf),', ' err', ')']116 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo << 1, err);')117 ['strprintf(', '"%s (%d)",', ' foo << 1,', ' err', ')']118 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo<bar>() >> 1, err);')119 ['strprintf(', '"%s (%d)",', ' foo<bar>() >> 1,', ' err', ')']120 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo < 1 ? bar : foobar, err);')121 ['strprintf(', '"%s (%d)",', ' foo < 1 ? bar : foobar,', ' err', ')']122 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo < 1, err);')123 ['strprintf(', '"%s (%d)",', ' foo < 1,', ' err', ')']124 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo > 1 ? bar : foobar, err);')125 ['strprintf(', '"%s (%d)",', ' foo > 1 ? bar : foobar,', ' err', ')']126 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo > 1, err);')127 ['strprintf(', '"%s (%d)",', ' foo > 1,', ' err', ')']128 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo <= 1, err);')129 ['strprintf(', '"%s (%d)",', ' foo <= 1,', ' err', ')']130 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo <= bar<1, 2>(1, 2), err);')131 ['strprintf(', '"%s (%d)",', ' foo <= bar<1, 2>(1, 2),', ' err', ')']132 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo>foo<1,2>(1,2)?bar:foobar,err)');133 ['strprintf(', '"%s (%d)",', ' foo>foo<1,2>(1,2)?bar:foobar,', 'err', ')']134 >>> parse_function_call_and_arguments("strprintf", 'strprintf("%s (%d)", foo>foo<1,2>(1,2),err)');135 ['strprintf(', '"%s (%d)",', ' foo>foo<1,2>(1,2),', 'err', ')']136 """137 assert type(function_name) is str and type(function_call) is str and function_name138 remaining = normalize(escape(function_call))139 expected_function_call = "{}(".format(function_name)140 assert remaining.startswith(expected_function_call)141 parts = [expected_function_call]142 remaining = remaining[len(expected_function_call):]143 open_parentheses = 1144 open_template_arguments = 0145 in_string = False146 parts.append("")147 for i, char in enumerate(remaining):148 parts.append(parts.pop() + char)149 if char == "\"":150 in_string = not in_string151 continue152 if in_string:153 continue154 if char == "(":155 open_parentheses += 1156 continue157 if char == ")":158 open_parentheses -= 1159 if open_parentheses > 1:160 continue161 if open_parentheses == 0:162 parts.append(parts.pop()[:-1])163 parts.append(char)164 break165 prev_char = remaining[i - 1] if i - 1 >= 0 else None166 next_char = remaining[i + 1] if i + 1 <= len(remaining) - 1 else None167 if char == "<" and next_char not in [" ", "<", "="] and prev_char not in [" ", "<"]:168 open_template_arguments += 1169 continue170 if char == ">" and next_char not in [" ", ">", "="] and prev_char not in [" ", ">"] and open_template_arguments > 0:171 open_template_arguments -= 1172 if open_template_arguments > 0:173 continue174 if char == ",":175 parts.append("")176 return parts177def parse_string_content(argument):178 """Return the text within quotes in string argument.179 >>> parse_string_content('1 "foo %d bar" 2')180 'foo %d bar'181 >>> parse_string_content('1 foobar 2')182 ''183 >>> parse_string_content('1 "bar" 2')184 'bar'185 >>> parse_string_content('1 "foo" 2 "bar" 3')186 'foobar'187 >>> parse_string_content('1 "foo" 2 " " "bar" 3')188 'foo bar'189 >>> parse_string_content('""')190 ''191 >>> parse_string_content('')192 ''193 >>> parse_string_content('1 2 3')194 ''195 """196 assert type(argument) is str197 string_content = ""198 in_string = False199 for char in normalize(escape(argument)):200 if char == "\"":201 in_string = not in_string202 elif in_string:203 string_content += char204 return string_content205def count_format_specifiers(format_string):206 """Return the number of format specifiers in string format_string.207 >>> count_format_specifiers("foo bar foo")208 0209 >>> count_format_specifiers("foo %d bar foo")210 1211 >>> count_format_specifiers("foo %d bar %i foo")212 2213 >>> count_format_specifiers("foo %d bar %i foo %% foo")214 2215 >>> count_format_specifiers("foo %d bar %i foo %% foo %d foo")216 3217 >>> count_format_specifiers("foo %d bar %i foo %% foo %*d foo")218 4219 """220 assert type(format_string) is str221 format_string = format_string.replace('%%', 'X')222 n = 0223 in_specifier = False224 for i, char in enumerate(format_string):225 if char == "%":226 in_specifier = True227 n += 1228 elif char in "aAcdeEfFgGinopsuxX":229 in_specifier = False230 elif in_specifier and char == "*":231 n += 1232 return n233def main():234 parser = argparse.ArgumentParser(description="This program checks that the number of arguments passed "235 "to a variadic format string function matches the number of format "236 "specifiers in the format string.")237 parser.add_argument("--skip-arguments", type=int, help="number of arguments before the format string "238 "argument (e.g. 1 in the case of fprintf)", default=0)239 parser.add_argument("function_name", help="function name (e.g. fprintf)", default=None)240 parser.add_argument("file", nargs="*", help="C++ source code file (e.g. foo.cpp)")241 args = parser.parse_args()242 exit_code = 0243 for filename in args.file:244 with open(filename, "r", encoding="utf-8") as f:245 for function_call_str in parse_function_calls(args.function_name, f.read()):246 parts = parse_function_call_and_arguments(args.function_name, function_call_str)247 relevant_function_call_str = unescape("".join(parts))[:512]248 if (f.name, relevant_function_call_str) in FALSE_POSITIVES:249 continue250 if len(parts) < 3 + args.skip_arguments:251 exit_code = 1252 print("{}: Could not parse function call string \"{}(...)\": {}".format(f.name, args.function_name, relevant_function_call_str))253 continue254 argument_count = len(parts) - 3 - args.skip_arguments255 format_str = parse_string_content(parts[1 + args.skip_arguments])256 format_specifier_count = count_format_specifiers(format_str)257 if format_specifier_count != argument_count:258 exit_code = 1259 print("{}: Expected {} argument(s) after format string but found {} argument(s): {}".format(f.name, format_specifier_count, argument_count, relevant_function_call_str))260 continue261 sys.exit(exit_code)262if __name__ == "__main__":...

Full Screen

Full Screen

test_shlex.py

Source:test_shlex.py Github

copy

Full Screen

1# -*- coding: iso-8859-1 -*-2import unittest3import shlex4from test import test_support5try:6 from cStringIO import StringIO7except ImportError:8 from StringIO import StringIO9# The original test data set was from shellwords, by Hartmut Goebel.10data = r"""x|x|11foo bar|foo|bar|12 foo bar|foo|bar|13 foo bar |foo|bar|14foo bar bla fasel|foo|bar|bla|fasel|15x y z xxxx|x|y|z|xxxx|16\x bar|\|x|bar|17\ x bar|\|x|bar|18\ bar|\|bar|19foo \x bar|foo|\|x|bar|20foo \ x bar|foo|\|x|bar|21foo \ bar|foo|\|bar|22foo "bar" bla|foo|"bar"|bla|23"foo" "bar" "bla"|"foo"|"bar"|"bla"|24"foo" bar "bla"|"foo"|bar|"bla"|25"foo" bar bla|"foo"|bar|bla|26foo 'bar' bla|foo|'bar'|bla|27'foo' 'bar' 'bla'|'foo'|'bar'|'bla'|28'foo' bar 'bla'|'foo'|bar|'bla'|29'foo' bar bla|'foo'|bar|bla|30blurb foo"bar"bar"fasel" baz|blurb|foo"bar"bar"fasel"|baz|31blurb foo'bar'bar'fasel' baz|blurb|foo'bar'bar'fasel'|baz|32""|""|33''|''|34foo "" bar|foo|""|bar|35foo '' bar|foo|''|bar|36foo "" "" "" bar|foo|""|""|""|bar|37foo '' '' '' bar|foo|''|''|''|bar|38\""|\|""|39"\"|"\"|40"foo\ bar"|"foo\ bar"|41"foo\\ bar"|"foo\\ bar"|42"foo\\ bar\"|"foo\\ bar\"|43"foo\\" bar\""|"foo\\"|bar|\|""|44"foo\\ bar\" dfadf"|"foo\\ bar\"|dfadf"|45"foo\\\ bar\" dfadf"|"foo\\\ bar\"|dfadf"|46"foo\\\x bar\" dfadf"|"foo\\\x bar\"|dfadf"|47"foo\x bar\" dfadf"|"foo\x bar\"|dfadf"|48\''|\|''|49'foo\ bar'|'foo\ bar'|50'foo\\ bar'|'foo\\ bar'|51"foo\\\x bar\" df'a\ 'df'|"foo\\\x bar\"|df'a|\|'df'|52\"foo"|\|"foo"|53\"foo"\x|\|"foo"|\|x|54"foo\x"|"foo\x"|55"foo\ "|"foo\ "|56foo\ xx|foo|\|xx|57foo\ x\x|foo|\|x|\|x|58foo\ x\x\""|foo|\|x|\|x|\|""|59"foo\ x\x"|"foo\ x\x"|60"foo\ x\x\\"|"foo\ x\x\\"|61"foo\ x\x\\""foobar"|"foo\ x\x\\"|"foobar"|62"foo\ x\x\\"\''"foobar"|"foo\ x\x\\"|\|''|"foobar"|63"foo\ x\x\\"\'"fo'obar"|"foo\ x\x\\"|\|'"fo'|obar"|64"foo\ x\x\\"\'"fo'obar" 'don'\''t'|"foo\ x\x\\"|\|'"fo'|obar"|'don'|\|''|t'|65'foo\ bar'|'foo\ bar'|66'foo\\ bar'|'foo\\ bar'|67foo\ bar|foo|\|bar|68foo#bar\nbaz|foobaz|69:-) ;-)|:|-|)|;|-|)|70áéíóú|á|é|í|ó|ú|71"""72posix_data = r"""x|x|73foo bar|foo|bar|74 foo bar|foo|bar|75 foo bar |foo|bar|76foo bar bla fasel|foo|bar|bla|fasel|77x y z xxxx|x|y|z|xxxx|78\x bar|x|bar|79\ x bar| x|bar|80\ bar| bar|81foo \x bar|foo|x|bar|82foo \ x bar|foo| x|bar|83foo \ bar|foo| bar|84foo "bar" bla|foo|bar|bla|85"foo" "bar" "bla"|foo|bar|bla|86"foo" bar "bla"|foo|bar|bla|87"foo" bar bla|foo|bar|bla|88foo 'bar' bla|foo|bar|bla|89'foo' 'bar' 'bla'|foo|bar|bla|90'foo' bar 'bla'|foo|bar|bla|91'foo' bar bla|foo|bar|bla|92blurb foo"bar"bar"fasel" baz|blurb|foobarbarfasel|baz|93blurb foo'bar'bar'fasel' baz|blurb|foobarbarfasel|baz|94""||95''||96foo "" bar|foo||bar|97foo '' bar|foo||bar|98foo "" "" "" bar|foo||||bar|99foo '' '' '' bar|foo||||bar|100\"|"|101"\""|"|102"foo\ bar"|foo\ bar|103"foo\\ bar"|foo\ bar|104"foo\\ bar\""|foo\ bar"|105"foo\\" bar\"|foo\|bar"|106"foo\\ bar\" dfadf"|foo\ bar" dfadf|107"foo\\\ bar\" dfadf"|foo\\ bar" dfadf|108"foo\\\x bar\" dfadf"|foo\\x bar" dfadf|109"foo\x bar\" dfadf"|foo\x bar" dfadf|110\'|'|111'foo\ bar'|foo\ bar|112'foo\\ bar'|foo\\ bar|113"foo\\\x bar\" df'a\ 'df"|foo\\x bar" df'a\ 'df|114\"foo|"foo|115\"foo\x|"foox|116"foo\x"|foo\x|117"foo\ "|foo\ |118foo\ xx|foo xx|119foo\ x\x|foo xx|120foo\ x\x\"|foo xx"|121"foo\ x\x"|foo\ x\x|122"foo\ x\x\\"|foo\ x\x\|123"foo\ x\x\\""foobar"|foo\ x\x\foobar|124"foo\ x\x\\"\'"foobar"|foo\ x\x\'foobar|125"foo\ x\x\\"\'"fo'obar"|foo\ x\x\'fo'obar|126"foo\ x\x\\"\'"fo'obar" 'don'\''t'|foo\ x\x\'fo'obar|don't|127"foo\ x\x\\"\'"fo'obar" 'don'\''t' \\|foo\ x\x\'fo'obar|don't|\|128'foo\ bar'|foo\ bar|129'foo\\ bar'|foo\\ bar|130foo\ bar|foo bar|131foo#bar\nbaz|foo|baz|132:-) ;-)|:-)|;-)|133áéíóú|áéíóú|134"""135class ShlexTest(unittest.TestCase):136 def setUp(self):137 self.data = [x.split("|")[:-1]138 for x in data.splitlines()]139 self.posix_data = [x.split("|")[:-1]140 for x in posix_data.splitlines()]141 for item in self.data:142 item[0] = item[0].replace(r"\n", "\n")143 for item in self.posix_data:144 item[0] = item[0].replace(r"\n", "\n")145 def splitTest(self, data, comments):146 for i in range(len(data)):147 l = shlex.split(data[i][0], comments=comments)148 self.assertEqual(l, data[i][1:],149 "%s: %s != %s" %150 (data[i][0], l, data[i][1:]))151 def oldSplit(self, s):152 ret = []153 lex = shlex.shlex(StringIO(s))154 tok = lex.get_token()155 while tok:156 ret.append(tok)157 tok = lex.get_token()158 return ret159 def testSplitPosix(self):160 """Test data splitting with posix parser"""161 self.splitTest(self.posix_data, comments=True)162 def testCompat(self):163 """Test compatibility interface"""164 for i in range(len(self.data)):165 l = self.oldSplit(self.data[i][0])166 self.assertEqual(l, self.data[i][1:],167 "%s: %s != %s" %168 (self.data[i][0], l, self.data[i][1:]))169# Allow this test to be used with old shlex.py170if not getattr(shlex, "split", None):171 for methname in dir(ShlexTest):172 if methname.startswith("test") and methname != "testCompat":173 delattr(ShlexTest, methname)174def test_main():175 test_support.run_unittest(ShlexTest)176if __name__ == "__main__":...

Full Screen

Full Screen

test_virtual_fs.py

Source:test_virtual_fs.py Github

copy

Full Screen

1from unittest.mock import patch2from zulip_bots.bots.virtual_fs.virtual_fs import sample_conversation3from zulip_bots.test_lib import BotTestCase, DefaultTests4class TestVirtualFsBot(BotTestCase, DefaultTests):5 bot_name = "virtual_fs"6 help_txt = (7 "foo@example.com:\n\nThis bot implements a virtual file system for a stream.\n"8 "The locations of text are persisted for the lifetime of the bot\n"9 "running, and if you rename a stream, you will lose the info.\n"10 "Example commands:\n\n```\n"11 "@mention-bot sample_conversation: sample conversation with the bot\n"12 "@mention-bot mkdir: create a directory\n"13 "@mention-bot ls: list a directory\n"14 "@mention-bot cd: change directory\n"15 "@mention-bot pwd: show current path\n"16 "@mention-bot write: write text\n"17 "@mention-bot read: read text\n"18 "@mention-bot rm: remove a file\n"19 "@mention-bot rmdir: remove a directory\n"20 "```\n"21 "Use commands like `@mention-bot help write` for more details on specific\ncommands.\n"22 )23 def test_multiple_recipient_conversation(self) -> None:24 expected = [25 ("mkdir home", "foo@example.com:\ndirectory created"),26 ]27 message = dict(28 display_recipient=[{"email": "foo@example.com"}, {"email": "boo@example.com"}],29 sender_email="foo@example.com",30 sender_full_name="Foo Test User",31 sender_id="123",32 content="mkdir home",33 )34 with patch("zulip_bots.test_lib.BotTestCase.make_request_message", return_value=message):35 self.verify_dialog(expected)36 def test_sample_conversation_help(self) -> None:37 # There's nothing terribly tricky about the "sample conversation,"38 # so we just do a quick sanity check.39 reply = self.get_reply_dict("sample_conversation")40 content = reply["content"]41 frag = "foo@example.com:\ncd /\nCurrent path: /\n\n"42 self.assertTrue(content.startswith(frag))43 frag = "read home/stuff/file1\nERROR: file does not exist\n\n"44 self.assertIn(frag, content)45 def test_sample_conversation(self) -> None:46 # The function sample_conversation is actually part of the47 # bot's implementation, because we render a sample conversation48 # for the user's benefit if they ask. But then we can also49 # use it to test that the bot works as advertised.50 expected = [51 (request, "foo@example.com:\n" + reply) for (request, reply) in sample_conversation()52 ]53 self.verify_dialog(expected)54 def test_commands_1(self) -> None:55 expected = [56 ("cd /home", "foo@example.com:\nERROR: invalid path"),57 ("mkdir home", "foo@example.com:\ndirectory created"),58 ("pwd", "foo@example.com:\n/"),59 ("help", self.help_txt),60 ("help ls", "foo@example.com:\nsyntax: ls <optional_path>"),61 ("", self.help_txt),62 ]63 self.verify_dialog(expected)64 def test_commands_2(self) -> None:65 expected = [66 ("help", self.help_txt),67 ("help ls", "foo@example.com:\nsyntax: ls <optional_path>"),68 ("help invalid", self.help_txt),69 ("", self.help_txt),70 ("write test hello world", "foo@example.com:\nfile written"),71 ("rmdir test", "foo@example.com:\nERROR: /*test* is a file, directory required"),72 ("cd test", "foo@example.com:\nERROR: /*test* is a file, directory required"),73 ("mkdir /foo/boo", "foo@example.com:\nERROR: /foo is not a directory"),74 ("pwd", "foo@example.com:\n/"),75 ("cd /home", "foo@example.com:\nERROR: invalid path"),76 ("mkdir etc", "foo@example.com:\ndirectory created"),77 ("mkdir home", "foo@example.com:\ndirectory created"),78 ("cd /home", "foo@example.com:\nCurrent path: /home/"),79 ("write test hello world", "foo@example.com:\nfile written"),80 ("rm test", "foo@example.com:\nremoved"),81 ("mkdir steve", "foo@example.com:\ndirectory created"),82 ("rmdir /home", "foo@example.com:\nremoved"),83 ("pwd", "foo@example.com:\nERROR: the current directory does not exist"),84 ("ls", "foo@example.com:\nERROR: file does not exist"),85 ("ls foo/", "foo@example.com:\nERROR: foo/ is not a valid name"),86 ("rm foo/", "foo@example.com:\nERROR: foo/ is not a valid name"),87 ("rmdir foo/", "foo@example.com:\nERROR: foo/ is not a valid name"),88 ("write foo/ a", "foo@example.com:\nERROR: foo/ is not a valid name"),89 ("read foo/", "foo@example.com:\nERROR: foo/ is not a valid name"),90 ("rmdir /foo", "foo@example.com:\nERROR: directory does not exist"),91 ]...

Full Screen

Full Screen

gc_test.py

Source:gc_test.py Github

copy

Full Screen

1# Copyright 2016 The TensorFlow Authors. All Rights Reserved.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14# ==============================================================================15"""Tests for session_bundle.gc."""16from __future__ import absolute_import17from __future__ import division18from __future__ import print_function19import os20import re21from six.moves import xrange # pylint: disable=redefined-builtin22import tensorflow as tf23from tensorflow.contrib.session_bundle import gc24from tensorflow.python.framework import test_util25from tensorflow.python.platform import gfile26def tearDownModule():27 gfile.DeleteRecursively(tf.test.get_temp_dir())28class GcTest(test_util.TensorFlowTestCase):29 def testLargestExportVersions(self):30 paths = [gc.Path("/foo", 8), gc.Path("/foo", 9), gc.Path("/foo", 10)]31 newest = gc.largest_export_versions(2)32 n = newest(paths)33 self.assertEquals(n, [gc.Path("/foo", 9), gc.Path("/foo", 10)])34 def testLargestExportVersionsDoesNotDeleteZeroFolder(self):35 paths = [gc.Path("/foo", 0), gc.Path("/foo", 3)]36 newest = gc.largest_export_versions(2)37 n = newest(paths)38 self.assertEquals(n, [gc.Path("/foo", 0), gc.Path("/foo", 3)])39 def testModExportVersion(self):40 paths = [gc.Path("/foo", 4), gc.Path("/foo", 5), gc.Path("/foo", 6),41 gc.Path("/foo", 9)]42 mod = gc.mod_export_version(2)43 self.assertEquals(mod(paths), [gc.Path("/foo", 4), gc.Path("/foo", 6)])44 mod = gc.mod_export_version(3)45 self.assertEquals(mod(paths), [gc.Path("/foo", 6), gc.Path("/foo", 9)])46 def testOneOfEveryNExportVersions(self):47 paths = [gc.Path("/foo", 0), gc.Path("/foo", 1), gc.Path("/foo", 3),48 gc.Path("/foo", 5), gc.Path("/foo", 6), gc.Path("/foo", 7),49 gc.Path("/foo", 8), gc.Path("/foo", 33)]50 one_of = gc.one_of_every_n_export_versions(3)51 self.assertEquals(one_of(paths),52 [gc.Path("/foo", 3), gc.Path("/foo", 6),53 gc.Path("/foo", 8), gc.Path("/foo", 33)])54 def testOneOfEveryNExportVersionsZero(self):55 # Zero is a special case since it gets rolled into the first interval.56 # Test that here.57 paths = [gc.Path("/foo", 0), gc.Path("/foo", 4), gc.Path("/foo", 5)]58 one_of = gc.one_of_every_n_export_versions(3)59 self.assertEquals(one_of(paths),60 [gc.Path("/foo", 0), gc.Path("/foo", 5)])61 def testUnion(self):62 paths = []63 for i in xrange(10):64 paths.append(gc.Path("/foo", i))65 f = gc.union(gc.largest_export_versions(3), gc.mod_export_version(3))66 self.assertEquals(67 f(paths), [gc.Path("/foo", 0), gc.Path("/foo", 3),68 gc.Path("/foo", 6), gc.Path("/foo", 7),69 gc.Path("/foo", 8), gc.Path("/foo", 9)])70 def testNegation(self):71 paths = [gc.Path("/foo", 4), gc.Path("/foo", 5), gc.Path("/foo", 6),72 gc.Path("/foo", 9)]73 mod = gc.negation(gc.mod_export_version(2))74 self.assertEquals(75 mod(paths), [gc.Path("/foo", 5), gc.Path("/foo", 9)])76 mod = gc.negation(gc.mod_export_version(3))77 self.assertEquals(78 mod(paths), [gc.Path("/foo", 4), gc.Path("/foo", 5)])79 def testPathsWithParse(self):80 base_dir = os.path.join(tf.test.get_temp_dir(), "paths_parse")81 self.assertFalse(gfile.Exists(base_dir))82 for p in xrange(3):83 gfile.MakeDirs(os.path.join(base_dir, "%d" % p))84 # add a base_directory to ignore85 gfile.MakeDirs(os.path.join(base_dir, "ignore"))86 # create a simple parser that pulls the export_version from the directory.87 def parser(path):88 match = re.match("^" + base_dir + "/(\\d+)$", path.path)89 if not match:90 return None91 return path._replace(export_version=int(match.group(1)))92 self.assertEquals(93 gc.get_paths(base_dir, parser=parser),94 [gc.Path(os.path.join(base_dir, "0"), 0),95 gc.Path(os.path.join(base_dir, "1"), 1),96 gc.Path(os.path.join(base_dir, "2"), 2)])97if __name__ == "__main__":...

Full Screen

Full Screen

test.py

Source:test.py Github

copy

Full Screen

1"""2Test that invalid uses of abstract fields are duly diagnosed and rejected.3"""4from contextlib import contextmanager5import langkit6from langkit.dsl import ASTNode, AbstractField, Field, NullField, T, abstract7from utils import emit_and_print_errors8@contextmanager9def test(label, lkt_file):10 print('== {} =='.format(label))11 yield12 emit_and_print_errors(lkt_file=lkt_file)13 langkit.reset()14 print()15with test('Not overriden', 'not-overriden.lkt'):16 class FooNode(ASTNode):17 pass18 class ExampleHolder(FooNode):19 f1 = AbstractField(T.FooNode)20 f2 = Field(type=T.FooNode)21 class Example(FooNode):22 token_node = True23 del FooNode, ExampleHolder, Example24with test('Partly overriden', 'partly-overriden.lkt'):25 class FooNode(ASTNode):26 pass27 @abstract28 class BaseExampleHolder(FooNode):29 f = AbstractField(T.FooNode)30 class SomeExampleHolder(BaseExampleHolder):31 f = Field()32 class OtherExampleHolder(BaseExampleHolder):33 pass34 class Example(FooNode):35 token_node = True36 del (FooNode, BaseExampleHolder, SomeExampleHolder, OtherExampleHolder,37 Example)38with test('Abstract overriding abstract', 'abstract-overriding-abstract.lkt'):39 class FooNode(ASTNode):40 pass41 @abstract42 class BaseExampleHolder(FooNode):43 f1 = AbstractField(T.FooNode)44 class ExampleHolder(BaseExampleHolder):45 f1 = AbstractField(T.FooNode)46 f2 = Field(type=T.FooNode)47 class Example(FooNode):48 token_node = True49 del FooNode, BaseExampleHolder, ExampleHolder, Example50with test('Abstract overriding concrete', 'abstract-overriding-concrete.lkt'):51 class FooNode(ASTNode):52 pass53 @abstract54 class BaseExampleHolder(FooNode):55 f = Field(type=T.FooNode)56 class ExampleHolder(BaseExampleHolder):57 f = AbstractField(T.FooNode)58 class Example(FooNode):59 token_node = True60 del FooNode, BaseExampleHolder, ExampleHolder, Example61with test('Inconsistent overriding type', 'inconsistent-overriding-type.lkt'):62 class FooNode(ASTNode):63 pass64 @abstract65 class BaseExampleHolder(FooNode):66 f = AbstractField(type=T.Example)67 class ExampleHolder(BaseExampleHolder):68 f = Field(type=T.FooNode)69 class Example(FooNode):70 token_node = True71 del FooNode, BaseExampleHolder, ExampleHolder, Example72with test('Free-standing null field', 'free-standing-null-field.lkt'):73 class FooNode(ASTNode):74 pass75 class ExampleHolder(FooNode):76 f = NullField()77 class Example(FooNode):78 token_node = True79 del FooNode, ExampleHolder, Example...

Full Screen

Full Screen

test_htmlhandlers.py

Source:test_htmlhandlers.py Github

copy

Full Screen

1import py2from py.__.apigen.rest.htmlhandlers import PageHandler3def test_breadcrumb():4 h = PageHandler()5 for fname, expected in [6 ('module_py', '<a href="module_py.html">py</a>'),7 ('module_py.test',8 '<a href="module_py.test.html">py.test</a>'),9 ('class_py.test',10 ('<a href="module_py.html">py</a>.'11 '<a href="class_py.test.html">test</a>')),12 ('class_py.test.foo',13 ('<a href="module_py.test.html">py.test</a>.'14 '<a href="class_py.test.foo.html">foo</a>')),15 ('class_py.test.foo.bar',16 ('<a href="module_py.test.foo.html">py.test.foo</a>.'17 '<a href="class_py.test.foo.bar.html">bar</a>')),18 ('function_foo', '<a href="function_foo.html">foo</a>'),19 ('function_foo.bar',20 ('<a href="module_foo.html">foo</a>.'21 '<a href="function_foo.bar.html">bar</a>')),22 ('function_foo.bar.baz',23 ('<a href="module_foo.bar.html">foo.bar</a>.'24 '<a href="function_foo.bar.baz.html">baz</a>')),25 ('method_foo.bar',26 ('<a href="class_foo.html">foo</a>.'27 '<a href="method_foo.bar.html">bar</a>')),28 ('method_foo.bar.baz',29 ('<a href="module_foo.html">foo</a>.'30 '<a href="class_foo.bar.html">bar</a>.'31 '<a href="method_foo.bar.baz.html">baz</a>')),32 ('method_foo.bar.baz.qux',33 ('<a href="module_foo.bar.html">foo.bar</a>.'34 '<a href="class_foo.bar.baz.html">baz</a>.'35 '<a href="method_foo.bar.baz.qux.html">qux</a>')),36 ]:37 html = ''.join([unicode(el) for el in h.breadcrumb(fname)])38 print fname39 print html...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var expect = require('chai').expect;2var foo = 'bar';3var beverages = { tea: [ 'chai', 'matcha', 'oolong' ] };4expect(foo).to.be.a('string');5expect(foo).to.equal('bar');6expect(foo).to.have.lengthOf(3);7expect(beverages).to.have.property('tea').with.lengthOf(3);

Full Screen

Using AI Code Generation

copy

Full Screen

1var foo = require('./foo');2var bar = require('./bar');3var baz = require('./baz');4foo().bar().baz();5module.exports = function () {6 console.log('Foo');7 return this;8};9module.exports = function () {10 console.log('Bar');11 return this;12};13module.exports = function () {14 console.log('Baz');15};16var foo = require('./foo');17var bar = require('./bar');18var baz = require('./baz');19foo().bar().baz();20module.exports = function () {21 console.log('Foo');22 return this;23};24module.exports = function () {25 console.log('Bar');26 return this;27};28module.exports = function () {29 console.log('Baz');30};31var foo = require('./foo');32var bar = require('./bar');33var baz = require('./baz');34foo().bar().baz();35module.exports = function () {36 console.log('Foo');37 return this;38};39module.exports = function () {40 console.log('Bar');41 return this;42};43module.exports = function () {44 console.log('Baz');45};46var foo = require('./foo');47var bar = require('./bar');48var baz = require('./baz');49foo().bar().baz();50module.exports = function () {51 console.log('Foo');52 return this;53};54module.exports = function () {55 console.log('Bar');56 return this;57};58module.exports = function () {59 console.log('Baz');60};61var foo = require('./foo');62var bar = require('./bar');63var baz = require('./baz');64foo().bar().baz();65module.exports = function () {66 console.log('Foo');67 return this;68};69module.exports = function ()

Full Screen

Using AI Code Generation

copy

Full Screen

1var chai = require('chai');2var expect = chai.expect;3var should = chai.should();4var assert = chai.assert;5describe('Testing Chai', function() {6 it('should not throw an error', function() {7 expect('foo').to.be.a('string');8 expect({ foo: 'bar' }).to.have.property('foo');9 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);10 expect(1).to.be.a('number');11 expect('foo').to.be.a('string');12 expect({ foo: 'bar' }).to.have.property('foo');13 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);14 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);15 expect(1).to.be.a('number');16 expect('foo').to.be.a('string');17 expect({ foo: 'bar' }).to.have.property('foo');18 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);19 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);20 expect(1).to.be.a('number');21 expect('foo').to.be.a('string');22 expect({ foo: 'bar' }).to.have.property('foo');23 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);24 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);25 expect(1).to.be.a('number');26 expect('foo').to.be.a('string');27 expect({ foo: 'bar' }).to.have.property('foo');28 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);29 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);30 expect(1).to.be.a('number');31 expect('foo').to.be.a('string');32 expect({ foo: 'bar' }).to.have.property('foo');33 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);34 expect({ foo: 'bar' }).to.have.property('foo').with.length(3);35 expect(1).to.be.a('number');36 expect('foo').to.be.a('string

Full Screen

Using AI Code Generation

copy

Full Screen

1var foo = require('foo');2var cc = new foo();3cc.foo("hello", function(err, result) {4 if (err) {5 console.log('error: ' + err);6 } else {7 console.log('result: ' + result);8 }9});

Full Screen

Using AI Code Generation

copy

Full Screen

1var Foo = require('foo');2var foo = new Foo();3foo.bar('hello world');4var Foo = function() {5 this.bar = function(msg) {6 console.log(msg);7 }8}9module.exports = Foo;10Here is a list of some of the most important built-in modules −

Full Screen

Using AI Code Generation

copy

Full Screen

1var foo = new Foo();2foo.bar();3var Foo = function() {4 this.bar = function() {5 }6}7var Bar = function() {8 this.baz = function() {9 }10}11var mockChaincode = {12 invoke: function() {13 return Q.resolve();14 }15};16var foo = new Foo(mockChaincode);17foo.bar();18var foo = new Foo();19foo.bar();20var Foo = function() {21 this.bar = function() {22 }23}24var Bar = function() {25 this.baz = function() {26 }27}28var mockChaincode = {29 invoke: function() {30 return Q.resolve();31 }32};33var foo = new Foo(mockChaincode);34foo.bar();35var Fabric_Client = require('fabric-client');36var path = require('path');37var util = require('util');

Full Screen

Using AI Code Generation

copy

Full Screen

1var chain = require('./chain');2chain.Foo();3module.exports = {4 Foo: function() {5 console.log('Foo');6 }7};8var chain = require('./chain');9chain.Foo();10module.exports = function() {11 console.log('Foo');12};13var chain = require('./chain');14chain();15module.exports = {16 Foo: function() {17 console.log('Foo');18 },19 Bar: function() {20 console.log('Bar');21 }22};23var chain = require('./chain');24chain.Foo();25chain.Bar();26In ES6, we have a new way of importing and exporting modules. The new syntax is much simpler and easier to read. We can import modules using the `import` keyword and export modules using the `export` keyword. 27export function Foo() {28 console.log('Foo');29}30import { Foo } from './chain';31Foo();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run chai automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful