How to use foo method in tempest

Best Python code snippet using tempest_python

test_alias.py

Source:test_alias.py Github

copy

Full Screen

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)...

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

...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', ')']...

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

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 tempest 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