Best JavaScript code snippet using sinon
test_alias.py
Source:test_alias.py
1# Copyright (c) The PyAMF Project.2# See LICENSE.txt for details.3"""4Tests for L{ClassAlias} and L{register_class}. Both are the most5fundamental parts of PyAMF and the test suite for it is big so it makes sense6to have them in one file.7@since: 0.58"""9import unittest10import pyamf11from pyamf import ClassAlias12from pyamf.tests.util import ClassCacheClearingTestCase, Spam, get_fqcn13try:14 set15except NameError:16 from sets import Set as set17class ClassAliasTestCase(ClassCacheClearingTestCase):18 """19 Test all functionality relating to the class L{ClassAlias}.20 """21 def test_init(self):22 x = ClassAlias(Spam)23 self.assertTrue(x.anonymous)24 self.assertTrue(x.dynamic)25 self.assertFalse(x.amf3)26 self.assertFalse(x.external)27 self.assertEqual(x.readonly_attrs, None)28 self.assertEqual(x.static_attrs, [])29 self.assertEqual(x.exclude_attrs, None)30 self.assertEqual(x.proxy_attrs, None)31 self.assertEqual(x.alias, '')32 self.assertEqual(x.klass, Spam)33 # compiled attributes34 self.assertEqual(x.decodable_properties, None)35 self.assertEqual(x.encodable_properties, None)36 self.assertTrue(x._compiled)37 def test_init_deferred(self):38 """39 Test for initial deferred compliation40 """41 x = ClassAlias(Spam, defer=True)42 self.assertTrue(x.anonymous)43 self.assertEqual(x.dynamic, None)44 self.assertFalse(x.amf3)45 self.assertFalse(x.external)46 self.assertEqual(x.readonly_attrs, None)47 self.assertEqual(x.static_attrs, None)48 self.assertEqual(x.exclude_attrs, None)49 self.assertEqual(x.proxy_attrs, None)50 self.assertEqual(x.alias, '')51 self.assertEqual(x.klass, Spam)52 # compiled attributes53 self.assertFalse(hasattr(x, 'static_properties'))54 self.assertFalse(x._compiled)55 def test_init_kwargs(self):56 x = ClassAlias(Spam, alias='foo', static_attrs=('bar',),57 exclude_attrs=('baz',), readonly_attrs='gak', amf3='spam',58 external='eggs', dynamic='goo', proxy_attrs=('blarg',))59 self.assertFalse(x.anonymous)60 self.assertEqual(x.dynamic, 'goo')61 self.assertEqual(x.amf3, 'spam')62 self.assertEqual(x.external, 'eggs')63 self.assertEqual(x.readonly_attrs, ['a', 'g', 'k'])64 self.assertEqual(x.static_attrs, ['bar'])65 self.assertEqual(x.exclude_attrs, ['baz'])66 self.assertEqual(x.proxy_attrs, ['blarg'])67 self.assertEqual(x.alias, 'foo')68 self.assertEqual(x.klass, Spam)69 # compiled attributes70 self.assertEqual(x.encodable_properties, ['bar'])71 self.assertEqual(x.decodable_properties, ['bar'])72 self.assertTrue(x._compiled)73 def test_bad_class(self):74 self.assertRaises(TypeError, ClassAlias, 'eggs', 'blah')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__, {})313 self.alias.applyAttributes(self.obj, attrs)314 self.assertEqual(self.obj.__dict__, {})315 def test_not_dynamic(self):316 self.alias.static_properties = None317 self.alias.dynamic = False318 attrs = {'foo': 'spam', 'bar': 'eggs'}319 self.assertEqual(self.obj.__dict__, {})320 self.alias.applyAttributes(self.obj, attrs)321 self.assertEqual(self.obj.__dict__, {})322 def test_dict(self):323 attrs = {'foo': 'spam', 'bar': 'eggs'}324 self.obj = Spam()325 self.assertEqual(self.obj.__dict__, {})326 self.alias.applyAttributes(self.obj, attrs)327 self.assertEqual(self.obj.__dict__, {'foo': 'spam', 'bar': 'eggs'})328class SimpleCompliationTestCase(unittest.TestCase):329 """330 Tests for L{ClassAlias} property compliation for no inheritance.331 """332 def test_compiled(self):333 x = ClassAlias(Spam, defer=True)334 self.assertFalse(x._compiled)335 x._compiled = True336 o = x.static_properties = object()337 x.compile()338 self.assertTrue(o is x.static_properties)339 def test_external(self):340 class A(object):341 pass342 class B:343 pass344 self.assertRaises(AttributeError, ClassAlias, A, external=True)345 self.assertRaises(AttributeError, ClassAlias, B, external=True)346 A.__readamf__ = None347 B.__readamf__ = None348 self.assertRaises(AttributeError, ClassAlias, A, external=True)349 self.assertRaises(AttributeError, ClassAlias, B, external=True)350 A.__readamf__ = lambda x: None351 B.__readamf__ = lambda x: None352 self.assertRaises(AttributeError, ClassAlias, A, external=True)353 self.assertRaises(AttributeError, ClassAlias, B, external=True)354 A.__writeamf__ = 'foo'355 B.__writeamf__ = 'bar'356 self.assertRaises(TypeError, ClassAlias, A, external=True)357 self.assertRaises(TypeError, ClassAlias, B, external=True)358 A.__writeamf__ = lambda x: None359 B.__writeamf__ = lambda x: None360 a = ClassAlias(A, external=True)361 b = ClassAlias(B, external=True)362 self.assertEqual(a.readonly_attrs, None)363 self.assertEqual(a.static_attrs, [])364 self.assertEqual(a.decodable_properties, None)365 self.assertEqual(a.encodable_properties, None)366 self.assertEqual(a.exclude_attrs, None)367 self.assertTrue(a.anonymous)368 self.assertTrue(a.external)369 self.assertTrue(a._compiled)370 self.assertEqual(a.klass, A)371 self.assertEqual(a.alias, '')372 # now b373 self.assertEqual(b.readonly_attrs, None)374 self.assertEqual(b.static_attrs, [])375 self.assertEqual(b.decodable_properties, None)376 self.assertEqual(b.encodable_properties, None)377 self.assertEqual(b.exclude_attrs, None)378 self.assertTrue(b.anonymous)379 self.assertTrue(b.external)380 self.assertTrue(b._compiled)381 self.assertEqual(b.klass, B)382 self.assertEqual(b.alias, '')383 def test_anonymous(self):384 x = ClassAlias(Spam, None)385 x.compile()386 self.assertTrue(x.anonymous)387 self.assertTrue(x._compiled)388 self.assertEqual(x.klass, Spam)389 self.assertEqual(x.alias, '')390 def test_exclude(self):391 x = ClassAlias(Spam, exclude_attrs=['foo', 'bar'], defer=True)392 self.assertEqual(x.exclude_attrs, ['foo', 'bar'])393 x.compile()394 self.assertEqual(x.exclude_attrs, ['bar', 'foo'])395 def test_readonly(self):396 x = ClassAlias(Spam, readonly_attrs=['foo', 'bar'], defer=True)397 self.assertEqual(x.readonly_attrs, ['foo', 'bar'])398 x.compile()399 self.assertEqual(x.readonly_attrs, ['bar', 'foo'])400 def test_static(self):401 x = ClassAlias(Spam, static_attrs=['foo', 'bar'], defer=True)402 self.assertEqual(x.static_attrs, ['foo', 'bar'])403 x.compile()404 self.assertEqual(x.static_attrs, ['foo', 'bar'])405 def test_custom_properties(self):406 class A(ClassAlias):407 def getCustomProperties(self):408 self.encodable_properties.update(['foo', 'bar'])409 self.decodable_properties.update(['bar', 'foo'])410 a = A(Spam)411 self.assertEqual(a.encodable_properties, ['bar', 'foo'])412 self.assertEqual(a.decodable_properties, ['bar', 'foo'])413 # test combined414 b = A(Spam, static_attrs=['foo', 'baz', 'gak'])415 self.assertEqual(b.encodable_properties, ['bar', 'baz', 'foo', 'gak'])416 self.assertEqual(b.decodable_properties, ['bar', 'baz', 'foo', 'gak'])417 def test_amf3(self):418 x = ClassAlias(Spam, amf3=True)419 self.assertTrue(x.amf3)420 def test_dynamic(self):421 x = ClassAlias(Spam, dynamic=True)422 self.assertTrue(x.dynamic)423 x = ClassAlias(Spam, dynamic=False)424 self.assertFalse(x.dynamic)425 x = ClassAlias(Spam)426 self.assertTrue(x.dynamic)427 def test_sealed_external(self):428 class A(object):429 __slots__ = ('foo',)430 class __amf__:431 external = True432 def __readamf__(self, foo):433 pass434 def __writeamf__(self, foo):435 pass436 x = ClassAlias(A)437 x.compile()438 self.assertTrue(x.sealed)439 def test_synonym_attrs(self):440 x = ClassAlias(Spam, synonym_attrs={'foo': 'bar'}, defer=True)441 self.assertEquals(x.synonym_attrs, {'foo': 'bar'})442 x.compile()443 self.assertEquals(x.synonym_attrs, {'foo': 'bar'})444class CompilationInheritanceTestCase(ClassCacheClearingTestCase):445 """446 """447 def _register(self, alias):448 pyamf.CLASS_CACHE[get_fqcn(alias.klass)] = alias449 pyamf.CLASS_CACHE[alias.klass] = alias450 return alias451 def test_bases(self):452 class A:453 pass454 class B(A):455 pass456 class C(B):457 pass458 a = self._register(ClassAlias(A, 'a', defer=True))459 b = self._register(ClassAlias(B, 'b', defer=True))460 c = self._register(ClassAlias(C, 'c', defer=True))461 self.assertEqual(a.bases, None)462 self.assertEqual(b.bases, None)463 self.assertEqual(c.bases, None)464 a.compile()465 self.assertEqual(a.bases, [])466 b.compile()467 self.assertEqual(a.bases, [])468 self.assertEqual(b.bases, [(A, a)])469 c.compile()470 self.assertEqual(a.bases, [])471 self.assertEqual(b.bases, [(A, a)])472 self.assertEqual(c.bases, [(B, b), (A, a)])473 def test_exclude_classic(self):474 class A:475 pass476 class B(A):477 pass478 class C(B):479 pass480 a = self._register(ClassAlias(A, 'a', exclude_attrs=['foo'], defer=True))481 b = self._register(ClassAlias(B, 'b', defer=True))482 c = self._register(ClassAlias(C, 'c', exclude_attrs=['bar'], defer=True))483 self.assertFalse(a._compiled)484 self.assertFalse(b._compiled)485 self.assertFalse(c._compiled)486 c.compile()487 self.assertTrue(a._compiled)488 self.assertTrue(b._compiled)489 self.assertTrue(c._compiled)490 self.assertEqual(a.exclude_attrs, ['foo'])491 self.assertEqual(b.exclude_attrs, ['foo'])492 self.assertEqual(c.exclude_attrs, ['bar', 'foo'])493 def test_exclude_new(self):494 class A(object):495 pass496 class B(A):497 pass498 class C(B):499 pass500 a = self._register(ClassAlias(A, 'a', exclude_attrs=['foo'], defer=True))501 b = self._register(ClassAlias(B, 'b', defer=True))502 c = self._register(ClassAlias(C, 'c', exclude_attrs=['bar'], defer=True))503 self.assertFalse(a._compiled)504 self.assertFalse(b._compiled)505 self.assertFalse(c._compiled)506 c.compile()507 self.assertTrue(a._compiled)508 self.assertTrue(b._compiled)509 self.assertTrue(c._compiled)510 self.assertEqual(a.exclude_attrs, ['foo'])511 self.assertEqual(b.exclude_attrs, ['foo'])512 self.assertEqual(c.exclude_attrs, ['bar', 'foo'])513 def test_readonly_classic(self):514 class A:515 pass516 class B(A):517 pass518 class C(B):519 pass520 a = self._register(ClassAlias(A, 'a', readonly_attrs=['foo'], defer=True))521 b = self._register(ClassAlias(B, 'b', defer=True))522 c = self._register(ClassAlias(C, 'c', readonly_attrs=['bar'], defer=True))523 self.assertFalse(a._compiled)524 self.assertFalse(b._compiled)525 self.assertFalse(c._compiled)526 c.compile()527 self.assertTrue(a._compiled)528 self.assertTrue(b._compiled)529 self.assertTrue(c._compiled)530 self.assertEqual(a.readonly_attrs, ['foo'])531 self.assertEqual(b.readonly_attrs, ['foo'])532 self.assertEqual(c.readonly_attrs, ['bar', 'foo'])533 def test_readonly_new(self):534 class A(object):535 pass536 class B(A):537 pass538 class C(B):539 pass540 a = self._register(ClassAlias(A, 'a', readonly_attrs=['foo'], defer=True))541 b = self._register(ClassAlias(B, 'b', defer=True))542 c = self._register(ClassAlias(C, 'c', readonly_attrs=['bar'], defer=True))543 self.assertFalse(a._compiled)544 self.assertFalse(b._compiled)545 self.assertFalse(c._compiled)546 c.compile()547 self.assertTrue(a._compiled)548 self.assertTrue(b._compiled)549 self.assertTrue(c._compiled)550 self.assertEqual(a.readonly_attrs, ['foo'])551 self.assertEqual(b.readonly_attrs, ['foo'])552 self.assertEqual(c.readonly_attrs, ['bar', 'foo'])553 def test_static_classic(self):554 class A:555 pass556 class B(A):557 pass558 class C(B):559 pass560 a = self._register(ClassAlias(A, 'a', static_attrs=['foo'], defer=True))561 b = self._register(ClassAlias(B, 'b', defer=True))562 c = self._register(ClassAlias(C, 'c', static_attrs=['bar'], defer=True))563 self.assertFalse(a._compiled)564 self.assertFalse(b._compiled)565 self.assertFalse(c._compiled)566 c.compile()567 self.assertTrue(a._compiled)568 self.assertTrue(b._compiled)569 self.assertTrue(c._compiled)570 self.assertEqual(a.static_attrs, ['foo'])571 self.assertEqual(b.static_attrs, ['foo'])572 self.assertEqual(c.static_attrs, ['foo', 'bar'])573 def test_static_new(self):574 class A(object):575 pass576 class B(A):577 pass578 class C(B):579 pass580 a = self._register(ClassAlias(A, 'a', static_attrs=['foo'], defer=True))581 b = self._register(ClassAlias(B, 'b', defer=True))582 c = self._register(ClassAlias(C, 'c', static_attrs=['bar'], defer=True))583 self.assertFalse(a._compiled)584 self.assertFalse(b._compiled)585 self.assertFalse(c._compiled)586 c.compile()587 self.assertTrue(a._compiled)588 self.assertTrue(b._compiled)589 self.assertTrue(c._compiled)590 self.assertEqual(a.static_attrs, ['foo'])591 self.assertEqual(b.static_attrs, ['foo'])592 self.assertEqual(c.static_attrs, ['foo', 'bar'])593 def test_amf3(self):594 class A:595 pass596 class B(A):597 pass598 class C(B):599 pass600 a = self._register(ClassAlias(A, 'a', amf3=True, defer=True))601 b = self._register(ClassAlias(B, 'b', defer=True))602 c = self._register(ClassAlias(C, 'c', amf3=False, defer=True))603 self.assertFalse(a._compiled)604 self.assertFalse(b._compiled)605 self.assertFalse(c._compiled)606 c.compile()607 self.assertTrue(a._compiled)608 self.assertTrue(b._compiled)609 self.assertTrue(c._compiled)610 self.assertTrue(a.amf3)611 self.assertTrue(b.amf3)612 self.assertFalse(c.amf3)613 def test_dynamic(self):614 class A:615 pass616 class B(A):617 pass618 class C(B):619 pass620 a = self._register(ClassAlias(A, 'a', dynamic=False, defer=True))621 b = self._register(ClassAlias(B, 'b', defer=True))622 c = self._register(ClassAlias(C, 'c', dynamic=True, defer=True))623 self.assertFalse(a._compiled)624 self.assertFalse(b._compiled)625 self.assertFalse(c._compiled)626 c.compile()627 self.assertTrue(a._compiled)628 self.assertTrue(b._compiled)629 self.assertTrue(c._compiled)630 self.assertFalse(a.dynamic)631 self.assertFalse(b.dynamic)632 self.assertTrue(c.dynamic)633 def test_synonym_attrs(self):634 class A(object):635 pass636 class B(A):637 pass638 class C(B):639 pass640 a = self._register(ClassAlias(A, 'a', synonym_attrs={'foo': 'bar', 'bar': 'baz'}, defer=True))641 b = self._register(ClassAlias(B, 'b', defer=True))642 c = self._register(ClassAlias(C, 'c', synonym_attrs={'bar': 'spam'}, defer=True))643 self.assertFalse(a._compiled)644 self.assertFalse(b._compiled)645 self.assertFalse(c._compiled)646 c.compile()647 self.assertTrue(a._compiled)648 self.assertTrue(b._compiled)649 self.assertTrue(c._compiled)650 self.assertEquals(a.synonym_attrs, {'foo': 'bar', 'bar': 'baz'})651 self.assertEquals(b.synonym_attrs, {'foo': 'bar', 'bar': 'baz'})652 self.assertEquals(c.synonym_attrs, {'foo': 'bar', 'bar': 'spam'})653class CompilationIntegrationTestCase(unittest.TestCase):654 """655 Integration tests for ClassAlias's656 """657 def test_slots_classic(self):658 class A:659 __slots__ = ('foo', 'bar')660 class B(A):661 __slots__ = ('gak',)662 class C(B):663 pass664 class D(C, B):665 __slots__ = ('spam',)666 a = ClassAlias(A)667 self.assertFalse(a.dynamic)668 self.assertEqual(a.encodable_properties, ['bar', 'foo'])669 self.assertEqual(a.decodable_properties, ['bar', 'foo'])670 b = ClassAlias(B)671 self.assertFalse(b.dynamic)672 self.assertEqual(b.encodable_properties, ['bar', 'foo', 'gak'])673 self.assertEqual(b.decodable_properties, ['bar', 'foo', 'gak'])674 c = ClassAlias(C)675 self.assertFalse(c.dynamic)676 self.assertEqual(c.encodable_properties, ['bar', 'foo', 'gak'])677 self.assertEqual(c.decodable_properties, ['bar', 'foo', 'gak'])678 d = ClassAlias(D)679 self.assertFalse(d.dynamic)680 self.assertEqual(d.encodable_properties, ['bar', 'foo', 'gak', 'spam'])681 self.assertEqual(d.decodable_properties, ['bar', 'foo', 'gak', 'spam'])682 def test_slots_new(self):683 class A(object):684 __slots__ = ('foo', 'bar')685 class B(A):686 __slots__ = ('gak',)687 class C(B):688 pass689 class D(C, B):690 __slots__ = ('spam',)691 a = ClassAlias(A)692 self.assertFalse(a.dynamic)693 self.assertEqual(a.encodable_properties, ['bar', 'foo'])694 self.assertEqual(a.decodable_properties, ['bar', 'foo'])695 b = ClassAlias(B)696 self.assertFalse(b.dynamic)697 self.assertEqual(b.encodable_properties, ['bar', 'foo', 'gak'])698 self.assertEqual(b.decodable_properties, ['bar', 'foo', 'gak'])699 c = ClassAlias(C)700 self.assertTrue(c.dynamic)701 self.assertEqual(c.encodable_properties, ['bar', 'foo', 'gak'])702 self.assertEqual(c.decodable_properties, ['bar', 'foo', 'gak'])703 d = ClassAlias(D)704 self.assertTrue(d.dynamic)705 self.assertEqual(d.encodable_properties, ['bar', 'foo', 'gak', 'spam'])706 self.assertEqual(d.decodable_properties, ['bar', 'foo', 'gak', 'spam'])707 def test_properties(self):708 class A:709 a_rw = property(lambda _: None, lambda _, x: None)710 a_ro = property(lambda _: None)711 class B(A):712 b_rw = property(lambda _: None, lambda _, x: None)713 b_ro = property(lambda _: None)714 class C(B):715 pass716 a = ClassAlias(A)717 self.assertTrue(a.dynamic)718 self.assertEqual(a.encodable_properties, ['a_ro', 'a_rw'])719 self.assertEqual(a.decodable_properties, ['a_rw'])720 b = ClassAlias(B)721 self.assertTrue(b.dynamic)722 self.assertEqual(b.encodable_properties, ['a_ro', 'a_rw', 'b_ro', 'b_rw'])723 self.assertEqual(b.decodable_properties, ['a_rw', 'b_rw'])724 c = ClassAlias(C)725 self.assertTrue(c.dynamic)726 self.assertEqual(c.encodable_properties, ['a_ro', 'a_rw', 'b_ro', 'b_rw'])727 self.assertEqual(c.decodable_properties, ['a_rw', 'b_rw'])728class RegisterClassTestCase(ClassCacheClearingTestCase):729 """730 Tests for L{pyamf.register_class}731 """732 def tearDown(self):733 ClassCacheClearingTestCase.tearDown(self)734 if hasattr(Spam, '__amf__'):735 del Spam.__amf__736 def test_meta(self):737 self.assertFalse('spam.eggs' in pyamf.CLASS_CACHE.keys())738 Spam.__amf__ = {739 'alias': 'spam.eggs'740 }741 alias = pyamf.register_class(Spam)742 self.assertTrue('spam.eggs' in pyamf.CLASS_CACHE.keys())743 self.assertEqual(pyamf.CLASS_CACHE['spam.eggs'], alias)744 self.assertTrue(isinstance(alias, pyamf.ClassAlias))745 self.assertEqual(alias.klass, Spam)746 self.assertEqual(alias.alias, 'spam.eggs')747 self.assertFalse(alias._compiled)748 def test_kwarg(self):749 self.assertFalse('spam.eggs' in pyamf.CLASS_CACHE.keys())750 alias = pyamf.register_class(Spam, 'spam.eggs')751 self.assertTrue('spam.eggs' in pyamf.CLASS_CACHE.keys())752 self.assertEqual(pyamf.CLASS_CACHE['spam.eggs'], alias)753 self.assertTrue(isinstance(alias, pyamf.ClassAlias))754 self.assertEqual(alias.klass, Spam)755 self.assertEqual(alias.alias, 'spam.eggs')756 self.assertFalse(alias._compiled)757class UnregisterClassTestCase(ClassCacheClearingTestCase):758 """759 Tests for L{pyamf.unregister_class}760 """761 def test_alias(self):762 self.assertFalse('foo' in pyamf.CLASS_CACHE)763 self.assertRaises(pyamf.UnknownClassAlias, pyamf.unregister_class, 'foo')764 def test_class(self):765 self.assertFalse(Spam in pyamf.CLASS_CACHE)766 self.assertRaises(pyamf.UnknownClassAlias, pyamf.unregister_class, Spam)767 def test_remove(self):768 alias = ClassAlias(Spam, 'foo', defer=True)769 pyamf.CLASS_CACHE['foo'] = alias770 pyamf.CLASS_CACHE[Spam] = alias771 self.assertFalse(alias.anonymous)772 ret = pyamf.unregister_class('foo')773 self.assertFalse('foo' in pyamf.CLASS_CACHE)774 self.assertFalse(Spam in pyamf.CLASS_CACHE)775 self.assertTrue(ret is alias)776 def test_anonymous(self):777 alias = ClassAlias(Spam, defer=True)778 pyamf.CLASS_CACHE['foo'] = alias779 pyamf.CLASS_CACHE[Spam] = alias780 self.assertTrue(alias.anonymous)781 ret = pyamf.unregister_class(Spam)782 self.assertTrue('foo' in pyamf.CLASS_CACHE)783 self.assertFalse(Spam in pyamf.CLASS_CACHE)...
test_auth.py
Source:test_auth.py
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)...
lint-format-strings.py
Source:lint-format-strings.py
...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', ')']...
test_shlex.py
Source:test_shlex.py
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__":...
test_virtual_fs.py
Source:test_virtual_fs.py
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 ]...
gc_test.py
Source:gc_test.py
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__":...
test.py
Source:test.py
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...
test_htmlhandlers.py
Source:test_htmlhandlers.py
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...
Using AI Code Generation
1sinon.stub(obj, 'foo').returns('bar');2sinon.stub(obj, 'foo').returns('bar');3sinon.stub(obj, 'foo').returns('bar');4sinon.stub(obj, 'foo').returns('bar');5sinon.stub(obj, 'foo').returns('bar');6sinon.stub(obj, 'foo').returns('bar');7sinon.stub(obj, 'foo').returns('bar');8sinon.stub(obj, 'foo').returns('bar');9sinon.stub(obj, 'foo').returns('bar');10sinon.stub(obj, 'foo').returns('bar');11sinon.stub(obj, 'foo').returns('bar');12sinon.stub(obj, 'foo').returns('bar');13sinon.stub(obj, 'foo').returns('bar');14sinon.stub(obj, 'foo').returns('bar');15sinon.stub(obj, 'foo').returns('bar');16sinon.stub(obj, 'foo').returns('bar');17sinon.stub(obj, 'foo').returns('bar');18sinon.stub(obj, 'foo').returns('bar');19sinon.stub(obj, 'foo').returns('bar');20### `no-constant-condition` (recommended)21if (false) {22}23while (true) {
Using AI Code Generation
1var foo = sinon.stub();2foo(42);3foo.withArgs(42).returns(1);4foo.withArgs(43).throws("TypeError");5foo.withArgs(44).yields(1, 2, 3);6foo.withArgs(45).yieldsOn({name: 'obj'}, 1, 2, 3);7foo.withArgs(46).yieldsTo('success', 1, 2, 3);8foo.withArgs(47).yieldsToOn('success', {name: 'obj'}, 1, 2, 3);9foo.withArgs(48).callsArg(0);10foo.withArgs(49).callsArgOn(0, {name: 'obj'});11foo.withArgs(50).callsArgWith(0, 1, 2, 3);12foo.withArgs(51).callsArgOnWith(0, {name: 'obj'}, 1, 2, 3);13foo.withArgs(52).callsArgAsync(0);14foo.withArgs(53).callsArgOnAsync(0, {name: 'obj'});15foo.withArgs(54).callsArgWithAsync(0, 1, 2, 3);16foo.withArgs(55).callsArgOnWithAsync(0, {name: 'obj'}, 1, 2, 3);17foo.withArgs(56).returnsArg(0);18foo.withArgs(57).returnsThis();19foo.withArgs(58).throwsArg(0);20foo.withArgs(59).throwsException(new Error('my error'));21foo.withArgs(60).throwsException(new TypeError('my error'));22foo.withArgs(61).throwsException('my error');23foo.withArgs(62).throwsException('TypeError');24foo.withArgs(63).throwsException(/my error/);25foo.withArgs(64).throwsException(function () {});26foo.withArgs(65).returnsThis();27foo.withArgs(66).returnsArg(0);28foo.withArgs(67).throwsArg(0);29foo.withArgs(68).callsArg(0);30foo.withArgs(69).callsArgWith(0, 1, 2, 3);31foo.withArgs(70).callsArgOn(0, {name: 'obj'});32foo.withArgs(71).callsArgOnWith(0, {name: 'obj'}, 1, 2, 3);33foo.withArgs(
Using AI Code Generation
1var expect = require('chai').use(require('sinon-chai')).expect;2var sinon = require('sinon');3var foo = {4 bar: function() {5 return 1;6 }7};8describe('foo', function() {9 it('should call bar', function() {10 var spy = sinon.spy(foo, 'bar');11 foo.bar();12 expect(spy).to.have.been.called;13 });14});
Using AI Code Generation
1sinon.foo();2var sinon = require('sinon');3sinon.foo();4require(['sinon'], function (sinon) {5 sinon.foo();6});7 sinon.foo();8See [CONTRIBUTING.md](
Using AI Code Generation
1sinon.foo();2### import sinon from 'sinon'3import sinon from 'sinon';4sinon.foo();5### import { foo } from 'sinon'6import { foo } from 'sinon';7foo();8### import * as sinon from 'sinon'9import * as sinon from 'sinon';10sinon.foo();11### import { default as sinon } from 'sinon'12import { default as sinon } from 'sinon';13sinon.foo();14### import sinon from 'sinon/pkg/sinon-esm.js'15import sinon from 'sinon/pkg/sinon-esm.js';16sinon.foo();17### import { foo } from 'sinon/pkg/sinon-esm.js'18import { foo } from 'sinon/pkg/sinon-esm.js';19foo();20### import * as sinon from 'sinon/pkg/sinon-esm.js'21import * as sinon from 'sinon/pkg/sinon-esm.js';22sinon.foo();23### import { default as sinon } from 'sinon/pkg/sinon-esm.js'24import { default as sinon } from 'sinon/pkg/sinon-esm.js';25sinon.foo();26### import sinon from 'sinon/pkg/sinon.js'27import sinon from 'sinon/pkg/sinon.js';28sinon.foo();29### import { foo } from 'sinon/pkg/sinon.js'30import { foo } from 'sinon/pkg/sinon.js';31foo();32### import * as sinon from 'sinon/pkg/sinon.js'33import * as sinon from 'sinon/pkg/sinon.js';34sinon.foo();35### import { default as sinon } from 'sinon/pkg/sinon.js'36import { default as sinon } from 'sinon/pkg/sinon.js';
Using AI Code Generation
1sinon.stub(foo, 'bar').returns(42);2foo.bar.restore();3sinon.mock(foo).expects("bar").once();4foo.bar();5foo.bar.restore();6var server = sinon.fakeServer.create();7server.respondWith("GET", "/test", [8 { "Content-Type": "application/json" },9 '{"name": "Sinon"}'10]);11server.respond();12server.restore();13var clock = sinon.useFakeTimers();14var callback = sinon.spy();15var interval = setInterval(callback, 1000);16clock.tick(5000);17clearInterval(interval);18clock.restore();19var xhr = sinon.useFakeXMLHttpRequest();20var requests = [];21xhr.onCreate = function (req) { requests.push(req); };22xhr.restore();
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!