How to use bunch method in hypothesis

Best Python code snippet using hypothesis

ordered_bunch.py

Source:ordered_bunch.py Github

copy

Full Screen

1#!/usr/bin/env python2""" OrderedBunch is a subclass of OrderedDict with attribute-style access.3 4 >>> b = OrderedBunch()5 >>> b.hello = 'world'6 >>> b.hello7 'world'8 >>> b['hello'] += "!"9 >>> b.hello10 'world!'11 >>> b.foo = OrderedBunch(lol=True)12 >>> b.foo.lol13 True14 >>> b.foo is b['foo']15 True16 17 It is safe to import * from this module:18 19 __all__ = ('OrderedBunch', 'ordered_bunchify','ordered_unbunchify')20 21 ordered_un/bunchify provide dictionary conversion; Bunches can also be22 converted via OrderedBunch.to/fromOrderedDict().23 24 original source:25 https://pypi.python.org/pypi/bunch26"""27from .ordered_dict import OrderedDict28## Compatability Issues...29#try:30# from collections import OrderedDict31#except ImportError:32# from ordered_dict import OrderedDict33class OrderedBunch(OrderedDict):34 """ A dictionary that provides attribute-style access.35 36 >>> b = OrderedBunch()37 >>> b.hello = 'world'38 >>> b.hello39 'world'40 >>> b['hello'] += "!"41 >>> b.hello42 'world!'43 >>> b.foo = OrderedBunch(lol=True)44 >>> b.foo.lol45 True46 >>> b.foo is b['foo']47 True48 49 A OrderedBunch is a subclass of dict; it supports all the methods a dict does...50 51 >>> b.keys()52 ['foo', 'hello']53 54 Including update()...55 56 >>> b.update({ 'ponies': 'are pretty!' }, hello=42)57 >>> print(repr(b))58 OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!')59 60 As well as iteration...61 62 >>> [ (k,b[k]) for k in b ]63 [('ponies', 'are pretty!'), ('foo', OrderedBunch(lol=True)), ('hello', 42)]64 65 And "splats".66 67 >>> "The {knights} who say {ni}!".format(**OrderedBunch(knights='lolcats', ni='can haz'))68 'The lolcats who say can haz!'69 70 See ordered_unbunchify/OrderedBunch.toOrderedDict, ordered_bunchify/OrderedBunch.fromOrderedDict for notes about conversion.71 """72 73 _initialized = False74 75 def __init__(self,*args,**kwarg):76 """ initializes the ordered dict77 """78 super(OrderedBunch,self).__init__(*args,**kwarg)79 self._initialized = True80 81 def __contains__(self, k):82 """ >>> b = OrderedBunch(ponies='are pretty!')83 >>> 'ponies' in b84 True85 >>> 'foo' in b86 False87 >>> b['foo'] = 4288 >>> 'foo' in b89 True90 >>> b.hello = 'hai'91 >>> 'hello' in b92 True93 """94 try:95 return hasattr(self, k) or dict.__contains__(self, k)96 except:97 return False98 99 # only called if k not found in normal places 100 def __getattr__(self, k):101 """ Gets key if it exists, otherwise throws AttributeError.102 103 nb. __getattr__ is only called if key is not found in normal places.104 105 >>> b = OrderedBunch(bar='baz', lol={})106 >>> b.foo107 Traceback (most recent call last):108 ...109 AttributeError: foo110 111 >>> b.bar112 'baz'113 >>> getattr(b, 'bar')114 'baz'115 >>> b['bar']116 'baz'117 118 >>> b.lol is b['lol']119 True120 >>> b.lol is getattr(b, 'lol')121 True122 """123 try:124 # Throws exception if not in prototype chain125 return object.__getattribute__(self, k)126 except AttributeError:127 try:128 return self[k]129 except KeyError:130 raise AttributeError(k)131 132 def __setattr__(self, k, v):133 """ Sets attribute k if it exists, otherwise sets key k. A KeyError134 raised by set-item (only likely if you subclass OrderedBunch) will 135 propagate as an AttributeError instead.136 137 >>> b = OrderedBunch(foo='bar', this_is='useful when subclassing')138 >>> b.values #doctest: +ELLIPSIS139 <built-in method values of OrderedBunch object at 0x...>140 >>> b.values = 'uh oh'141 >>> b.values142 'uh oh'143 >>> b['values']144 Traceback (most recent call last):145 ...146 KeyError: 'values'147 """148 149 if not self._initialized:150 # for OrderedDict initialization151 return object.__setattr__(self, k, v)152 153 try:154 # Throws exception if not in prototype chain155 object.__getattribute__(self, k)156 except AttributeError:157 try:158 self[k] = v159 except:160 raise AttributeError(k)161 else:162 object.__setattr__(self, k, v)163 164 def __delattr__(self, k):165 """ Deletes attribute k if it exists, otherwise deletes key k. A KeyError166 raised by deleting the key--such as when the key is missing--will167 propagate as an AttributeError instead.168 169 >>> b = OrderedBunch(lol=42)170 >>> del b.values171 Traceback (most recent call last):172 ...173 AttributeError: 'OrderedBunch' object attribute 'values' is read-only174 >>> del b.lol175 >>> b.lol176 Traceback (most recent call last):177 ...178 AttributeError: lol179 """180 try:181 # Throws exception if not in prototype chain182 object.__getattribute__(self, k)183 except AttributeError:184 try:185 del self[k]186 except KeyError:187 raise AttributeError(k)188 else:189 object.__delattr__(self, k)190 191 def toOrderedDict(self):192 """ Recursively converts a bunch back into a dictionary.193 194 >>> b = OrderedBunch(OrderedBunchunch(lol=True), hello=42, ponies='are pretty!')195 >>> b.toOrderedDict()196 {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42}197 198 See ordered_unbunchify for more info.199 """200 return ordered_unbunchify(self)201 202 def __repr__(self):203 """ Invertible* string-form of a OrderedBunch.204 205 >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!')206 >>> print(repr(b))207 OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!')208 >>> eval(repr(b))209 OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!')210 211 (*) Invertible so long as collection contents are each repr-invertible.212 """213 keys = self.keys()214 args = ', '.join(['%s=%r' % (key, self[key]) for key in keys])215 return '%s(%s)' % (self.__class__.__name__, args)216 217 def __str__(self):218 """ String-form of a Bunch.219 """220 keys = self.keys()221 args = ', '.join(['%s=%r' % (key, self[key]) for key in keys])222 return '{%s}' % args 223 224 @staticmethod225 def fromOrderedDict(d):226 """ Recursively transforms a dictionary into a OrderedBunch via copy.227 228 >>> b = OrderedBunch.fromOrderedDict({'urmom': {'sez': {'what': 'what'}}})229 >>> b.urmom.sez.what230 'what'231 232 See ordered_bunchify for more info.233 """234 return ordered_bunchify(d)235# While we could convert abstract types like Mapping or Iterable, I think236# ordered_bunchify is more likely to "do what you mean" if it is conservative about237# casting (ex: isinstance(str,Iterable) == True ).238#239# Should you disagree, it is not difficult to duplicate this function with240# more aggressive coercion to suit your own purposes.241def ordered_bunchify(x):242 """ Recursively transforms a dictionary into a OrderedBunch via copy.243 244 >>> b = ordered_bunchify({'urmom': {'sez': {'what': 'what'}}})245 >>> b.urmom.sez.what246 'what'247 248 ordered_bunchify can handle intermediary dicts, lists and tuples (as well as 249 their subclasses), but ymmv on custom datatypes.250 251 >>> b = ordered_bunchify({ 'lol': ('cats', {'hah':'i win again'}), 252 ... 'hello': [{'french':'salut', 'german':'hallo'}] })253 >>> b.hello[0].french254 'salut'255 >>> b.lol[1].hah256 'i win again'257 258 nb. As dicts are not hashable, they cannot be nested in sets/frozensets.259 """260 if isinstance(x, dict):261 return OrderedBunch( (k, ordered_bunchify(v)) for k,v in x.iteritems() )262 elif isinstance(x, (list, tuple)):263 return type(x)( ordered_bunchify(v) for v in x )264 else:265 return x266def ordered_unbunchify(x):267 """ Recursively converts a OrderedBunch into a dictionary.268 269 >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!')270 >>> ordered_unbunchify(b)271 {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42}272 273 ordered_unbunchify will handle intermediary dicts, lists and tuples (as well as274 their subclasses), but ymmv on custom datatypes.275 276 >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42, 277 ... ponies=('are pretty!', OrderedBunch(lies='are trouble!')))278 >>> ordered_unbunchify(b) #doctest: +NORMALIZE_WHITESPACE279 {'ponies': ('are pretty!', {'lies': 'are trouble!'}), 280 'foo': ['bar', {'lol': True}], 'hello': 42}281 282 nb. As dicts are not hashable, they cannot be nested in sets/frozensets.283 """284 if isinstance(x, OrderedDict):285 return OrderedDict( (k, ordered_unbunchify(v)) for k,v in x.iteritems() ) 286 elif isinstance(x, dict):287 return dict( (k, ordered_unbunchify(v)) for k,v in x.iteritems() )288 elif isinstance(x, (list, tuple)):289 return type(x)( ordered_unbunchify(v) for v in x )290 else:291 return x292### Serialization293try:294 try:295 import json296 except ImportError:297 import simplejson as json298 299 def toJSON(self, **options):300 """ Serializes this OrderedBunch to JSON. Accepts the same keyword options as `json.dumps()`.301 302 >>> b = OrderedBunch(foo=OrderedBunch(lol=True), hello=42, ponies='are pretty!')303 >>> json.dumps(b)304 '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'305 >>> b.toJSON()306 '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'307 """308 return json.dumps(self, **options)309 310 OrderedBunch.toJSON = toJSON311 312except ImportError:313 pass314try:315 # Attempt to register ourself with PyYAML as a representer316 import yaml317 from yaml.representer import Representer, SafeRepresenter318 319 def from_yaml(loader, node):320 """ PyYAML support for Bunches using the tag `!bunch` and `!bunch.OrderedBunch`.321 322 >>> import yaml323 >>> yaml.load('''324 ... Flow style: !bunch.OrderedBunch { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki }325 ... Block style: !bunch326 ... Clark : Evans327 ... Brian : Ingerson328 ... Oren : Ben-Kiki329 ... ''') #doctest: +NORMALIZE_WHITESPACE330 {'Flow style': OrderedBunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki'), 331 'Block style': OrderedBunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki')}332 333 This module registers itself automatically to cover both OrderedBunch and any 334 subclasses. Should you want to customize the representation of a subclass,335 simply register it with PyYAML yourself.336 """337 data = OrderedBunch()338 yield data339 value = loader.construct_mapping(node)340 data.update(value)341 342 343 def to_yaml_safe(dumper, data):344 """ Converts OrderedBunch to a normal mapping node, making it appear as a345 dict in the YAML output.346 347 >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42)348 >>> import yaml349 >>> yaml.safe_dump(b, default_flow_style=True)350 '{foo: [bar, {lol: true}], hello: 42}\\n'351 """352 return dumper.represent_dict(data)353 354 def to_yaml(dumper, data):355 """ Converts OrderedBunch to a representation node.356 357 >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42)358 >>> import yaml359 >>> yaml.dump(b, default_flow_style=True)360 '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n'361 """362 return dumper.represent_mapping(u'!orderedbunch.OrderedBunch', data)363 364 365 yaml.add_constructor(u'!orderedbunch', from_yaml)366 yaml.add_constructor(u'!orderedbunch.OrderedBunch', from_yaml)367 368 SafeRepresenter.add_representer(OrderedBunch, to_yaml_safe)369 SafeRepresenter.add_multi_representer(OrderedBunch, to_yaml_safe)370 371 Representer.add_representer(OrderedBunch, to_yaml)372 Representer.add_multi_representer(OrderedBunch, to_yaml)373 374 375 # Instance methods for YAML conversion376 def toYAML(self, **options):377 """ Serializes this OrderedBunch to YAML, using `yaml.safe_dump()` if 378 no `Dumper` is provided. See the PyYAML documentation for more info.379 380 >>> b = OrderedBunch(foo=['bar', OrderedBunch(lol=True)], hello=42)381 >>> import yaml382 >>> yaml.safe_dump(b, default_flow_style=True)383 '{foo: [bar, {lol: true}], hello: 42}\\n'384 >>> b.toYAML(default_flow_style=True)385 '{foo: [bar, {lol: true}], hello: 42}\\n'386 >>> yaml.dump(b, default_flow_style=True)387 '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n'388 >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True)389 '!bunch.OrderedBunch {foo: [bar, !bunch.OrderedBunch {lol: true}], hello: 42}\\n'390 """391 opts = dict(indent=4, default_flow_style=False)392 opts.update(options)393 if 'Dumper' not in opts:394 return yaml.safe_dump(self, **opts)395 else:396 return yaml.dump(self, **opts)397 398 def fromYAML(*args, **kwargs):399 return ordered_bunchify( yaml.load(*args, **kwargs) )400 401 OrderedBunch.toYAML = OrderedBunch.__repr__ = toYAML402 OrderedBunch.fromYAML = staticmethod(fromYAML)403 404except ImportError:...

Full Screen

Full Screen

bunch.py

Source:bunch.py Github

copy

Full Screen

1#!/usr/bin/env python2""" Bunch is a subclass of dict with attribute-style access.3 4 >>> b = Bunch()5 >>> b.hello = 'world'6 >>> b.hello7 'world'8 >>> b['hello'] += "!"9 >>> b.hello10 'world!'11 >>> b.foo = Bunch(lol=True)12 >>> b.foo.lol13 True14 >>> b.foo is b['foo']15 True16 17 It is safe to import * from this module:18 19 __all__ = ('Bunch', 'bunchify','unbunchify')20 21 un/bunchify provide dictionary conversion; Bunches can also be22 converted via Bunch.to/fromDict().23 24 original source:25 https://pypi.python.org/pypi/bunch26"""27class Bunch(dict):28 """ A dictionary that provides attribute-style access.29 30 >>> b = Bunch()31 >>> b.hello = 'world'32 >>> b.hello33 'world'34 >>> b['hello'] += "!"35 >>> b.hello36 'world!'37 >>> b.foo = Bunch(lol=True)38 >>> b.foo.lol39 True40 >>> b.foo is b['foo']41 True42 43 A Bunch is a subclass of dict; it supports all the methods a dict does...44 45 >>> b.keys()46 ['foo', 'hello']47 48 Including update()...49 50 >>> b.update({ 'ponies': 'are pretty!' }, hello=42)51 >>> print(repr(b))52 Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')53 54 As well as iteration...55 56 >>> [ (k,b[k]) for k in b ]57 [('ponies', 'are pretty!'), ('foo', Bunch(lol=True)), ('hello', 42)]58 59 And "splats".60 61 >>> "The {knights} who say {ni}!".format(**Bunch(knights='lolcats', ni='can haz'))62 'The lolcats who say can haz!'63 64 See unbunchify/Bunch.toDict, bunchify/Bunch.fromDict for notes about conversion.65 """66 67 def __contains__(self, k):68 """ >>> b = Bunch(ponies='are pretty!')69 >>> 'ponies' in b70 True71 >>> 'foo' in b72 False73 >>> b['foo'] = 4274 >>> 'foo' in b75 True76 >>> b.hello = 'hai'77 >>> 'hello' in b78 True79 """80 try:81 return hasattr(self, k) or dict.__contains__(self, k)82 except:83 return False84 85 # only called if k not found in normal places 86 def __getattr__(self, k):87 """ Gets key if it exists, otherwise throws AttributeError.88 89 nb. __getattr__ is only called if key is not found in normal places.90 91 >>> b = Bunch(bar='baz', lol={})92 >>> b.foo93 Traceback (most recent call last):94 ...95 AttributeError: foo96 97 >>> b.bar98 'baz'99 >>> getattr(b, 'bar')100 'baz'101 >>> b['bar']102 'baz'103 104 >>> b.lol is b['lol']105 True106 >>> b.lol is getattr(b, 'lol')107 True108 """109 try:110 # Throws exception if not in prototype chain111 return object.__getattribute__(self, k)112 except AttributeError:113 try:114 return self[k]115 except KeyError:116 raise AttributeError(k)117 118 def __setattr__(self, k, v):119 """ Sets attribute k if it exists, otherwise sets key k. A KeyError120 raised by set-item (only likely if you subclass Bunch) will 121 propagate as an AttributeError instead.122 123 >>> b = Bunch(foo='bar', this_is='useful when subclassing')124 >>> b.values #doctest: +ELLIPSIS125 <built-in method values of Bunch object at 0x...>126 >>> b.values = 'uh oh'127 >>> b.values128 'uh oh'129 >>> b['values']130 Traceback (most recent call last):131 ...132 KeyError: 'values'133 """134 try:135 # Throws exception if not in prototype chain136 object.__getattribute__(self, k)137 except AttributeError:138 try:139 self[k] = v140 except:141 raise AttributeError(k)142 else:143 object.__setattr__(self, k, v)144 145 def __delattr__(self, k):146 """ Deletes attribute k if it exists, otherwise deletes key k. A KeyError147 raised by deleting the key--such as when the key is missing--will148 propagate as an AttributeError instead.149 150 >>> b = Bunch(lol=42)151 >>> del b.values152 Traceback (most recent call last):153 ...154 AttributeError: 'Bunch' object attribute 'values' is read-only155 >>> del b.lol156 >>> b.lol157 Traceback (most recent call last):158 ...159 AttributeError: lol160 """161 try:162 # Throws exception if not in prototype chain163 object.__getattribute__(self, k)164 except AttributeError:165 try:166 del self[k]167 except KeyError:168 raise AttributeError(k)169 else:170 object.__delattr__(self, k)171 172 def toDict(self):173 """ Recursively converts a bunch back into a dictionary.174 175 >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')176 >>> b.toDict()177 {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42}178 179 See unbunchify for more info.180 """181 return unbunchify(self)182 183 def __repr__(self):184 """ Invertible* string-form of a Bunch.185 186 >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')187 >>> print(repr(b))188 Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')189 >>> eval(repr(b))190 Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')191 192 (*) Invertible so long as collection contents are each repr-invertible.193 """194 keys = self.keys()195 keys.sort()196 args = ', '.join(['%s=%r' % (key, self[key]) for key in keys])197 return '%s(%s)' % (self.__class__.__name__, args)198 199 def __str__(self):200 """ String-form of a OrderedBunch.201 """202 keys = self.keys()203 keys.sort()204 args = ', '.join(['%s=%r' % (key, self[key]) for key in keys])205 return '{%s}' % args206 207 @staticmethod208 def fromDict(d):209 """ Recursively transforms a dictionary into a Bunch via copy.210 211 >>> b = Bunch.fromDict({'urmom': {'sez': {'what': 'what'}}})212 >>> b.urmom.sez.what213 'what'214 215 See bunchify for more info.216 """217 return bunchify(d)218# While we could convert abstract types like Mapping or Iterable, I think219# bunchify is more likely to "do what you mean" if it is conservative about220# casting (ex: isinstance(str,Iterable) == True ).221#222# Should you disagree, it is not difficult to duplicate this function with223# more aggressive coercion to suit your own purposes.224def bunchify(x):225 """ Recursively transforms a dictionary into a Bunch via copy.226 227 >>> b = bunchify({'urmom': {'sez': {'what': 'what'}}})228 >>> b.urmom.sez.what229 'what'230 231 bunchify can handle intermediary dicts, lists and tuples (as well as 232 their subclasses), but ymmv on custom datatypes.233 234 >>> b = bunchify({ 'lol': ('cats', {'hah':'i win again'}), 235 ... 'hello': [{'french':'salut', 'german':'hallo'}] })236 >>> b.hello[0].french237 'salut'238 >>> b.lol[1].hah239 'i win again'240 241 nb. As dicts are not hashable, they cannot be nested in sets/frozensets.242 """243 if isinstance(x, dict):244 return Bunch( (k, bunchify(v)) for k,v in x.iteritems() )245 elif isinstance(x, (list, tuple)):246 return type(x)( bunchify(v) for v in x )247 else:248 return x249def unbunchify(x):250 """ Recursively converts a Bunch into a dictionary.251 252 >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')253 >>> unbunchify(b)254 {'ponies': 'are pretty!', 'foo': {'lol': True}, 'hello': 42}255 256 unbunchify will handle intermediary dicts, lists and tuples (as well as257 their subclasses), but ymmv on custom datatypes.258 259 >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42, 260 ... ponies=('are pretty!', Bunch(lies='are trouble!')))261 >>> unbunchify(b) #doctest: +NORMALIZE_WHITESPACE262 {'ponies': ('are pretty!', {'lies': 'are trouble!'}), 263 'foo': ['bar', {'lol': True}], 'hello': 42}264 265 nb. As dicts are not hashable, they cannot be nested in sets/frozensets.266 """267 if isinstance(x, dict):268 return dict( (k, unbunchify(v)) for k,v in x.iteritems() )269 elif isinstance(x, (list, tuple)):270 return type(x)( unbunchify(v) for v in x )271 else:272 return x273### Serialization274try:275 try:276 import json277 except ImportError:278 import simplejson as json279 280 def toJSON(self, **options):281 """ Serializes this Bunch to JSON. Accepts the same keyword options as `json.dumps()`.282 283 >>> b = Bunch(foo=Bunch(lol=True), hello=42, ponies='are pretty!')284 >>> json.dumps(b)285 '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'286 >>> b.toJSON()287 '{"ponies": "are pretty!", "foo": {"lol": true}, "hello": 42}'288 """289 return json.dumps(self, **options)290 291 Bunch.toJSON = toJSON292 293except ImportError:294 pass295try:296 # Attempt to register ourself with PyYAML as a representer297 import yaml298 from yaml.representer import Representer, SafeRepresenter299 300 def from_yaml(loader, node):301 """ PyYAML support for Bunches using the tag `!bunch` and `!bunch.Bunch`.302 303 >>> import yaml304 >>> yaml.load('''305 ... Flow style: !bunch.Bunch { Clark: Evans, Brian: Ingerson, Oren: Ben-Kiki }306 ... Block style: !bunch307 ... Clark : Evans308 ... Brian : Ingerson309 ... Oren : Ben-Kiki310 ... ''') #doctest: +NORMALIZE_WHITESPACE311 {'Flow style': Bunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki'), 312 'Block style': Bunch(Brian='Ingerson', Clark='Evans', Oren='Ben-Kiki')}313 314 This module registers itself automatically to cover both Bunch and any 315 subclasses. Should you want to customize the representation of a subclass,316 simply register it with PyYAML yourself.317 """318 data = Bunch()319 yield data320 value = loader.construct_mapping(node)321 data.update(value)322 323 324 def to_yaml_safe(dumper, data):325 """ Converts Bunch to a normal mapping node, making it appear as a326 dict in the YAML output.327 328 >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42)329 >>> import yaml330 >>> yaml.safe_dump(b, default_flow_style=True)331 '{foo: [bar, {lol: true}], hello: 42}\\n'332 """333 return dumper.represent_dict(data)334 335 def to_yaml(dumper, data):336 """ Converts Bunch to a representation node.337 338 >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42)339 >>> import yaml340 >>> yaml.dump(b, default_flow_style=True)341 '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n'342 """343 return dumper.represent_mapping(u'!bunch.Bunch', data)344 345 346 yaml.add_constructor(u'!bunch', from_yaml)347 yaml.add_constructor(u'!bunch.Bunch', from_yaml)348 349 SafeRepresenter.add_representer(Bunch, to_yaml_safe)350 SafeRepresenter.add_multi_representer(Bunch, to_yaml_safe)351 352 Representer.add_representer(Bunch, to_yaml)353 Representer.add_multi_representer(Bunch, to_yaml)354 355 356 # Instance methods for YAML conversion357 def toYAML(self, **options):358 """ Serializes this Bunch to YAML, using `yaml.safe_dump()` if 359 no `Dumper` is provided. See the PyYAML documentation for more info.360 361 >>> b = Bunch(foo=['bar', Bunch(lol=True)], hello=42)362 >>> import yaml363 >>> yaml.safe_dump(b, default_flow_style=True)364 '{foo: [bar, {lol: true}], hello: 42}\\n'365 >>> b.toYAML(default_flow_style=True)366 '{foo: [bar, {lol: true}], hello: 42}\\n'367 >>> yaml.dump(b, default_flow_style=True)368 '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n'369 >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True)370 '!bunch.Bunch {foo: [bar, !bunch.Bunch {lol: true}], hello: 42}\\n'371 """372 opts = dict(indent=4, default_flow_style=False)373 opts.update(options)374 if 'Dumper' not in opts:375 return yaml.safe_dump(self, **opts)376 else:377 return yaml.dump(self, **opts)378 379 def fromYAML(*args, **kwargs):380 return bunchify( yaml.load(*args, **kwargs) )381 382 Bunch.toYAML = Bunch.__repr__ = toYAML383 Bunch.fromYAML = staticmethod(fromYAML)384 385except ImportError:...

Full Screen

Full Screen

NsBunchConfReader.py

Source:NsBunchConfReader.py Github

copy

Full Screen

1import sys2import os3import random4import json5import random6import networkx as nx7import MultiDomainConfReader as MDCR8sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__),9 '../src')))10from vnfsMapping import MultiDomain as MD11from vnfsMapping import NS12from vnfsMapping import NsMapper as NSM13from vnfsMapping import NsMapping as NSm14from vnfsMapping import NsGenerator as NSG15# 16absPath = os.path.abspath(os.path.dirname(__file__))17configPath = '/'.join(absPath.split('/')[:-1]) + '/simulation-configs'18class NsBunchConfReader(object):19 """Class to read NS bunch configuration files"""20 def __init__(self, simName):21 """Initialize the reader instance22 :simName: name of the simulation23 """24 self.__simName = simName25 26 def __readConfig(self):27 """Reads the configuration file for the NsBunch28 :returns: dictionary, None in case of error29 """30 filePath = configPath + '/' + self.__simName + '/nsBunch.json'31 if not os.path.exists(filePath):32 return None33 nsBunchProperties = None34 with open(filePath) as f:35 nsBunchProperties = json.load(f)36 return nsBunchProperties37 def readDumped(self, multiDomain=None):38 """Reads an already dumped NS bunch based in the configuration file39 of the simulation.40 :multiDomain: MultiDomain instance, if not provided, it will be41 read/created from the simulation files under the directory42 :returns: [NS bunch list, entryPoint list]43 [None, None] if no Ns bunch have been created44 """45 if not os.path.exists(configPath + '/' + self.__simName +\46 '/nsBunch'):47 return None, None48 nsBunch = NSG.NSgenerator.readNsBunch('nsBunch',49 baseAbsPath=configPath + '/' + self.__simName)50 entryPoints = self.__genEntryPoints(len(nsBunch),51 multiDomain=multiDomain)52 return nsBunch, entryPoints53 def __genEntryPoints(self, requests, multiDomain=None):54 """Generates the entry points list. This implies writting the JSON file55 or reading it, if it has already been created.56 :requests: number of requests to obtain entry points from57 :multiDomain: MultiDomain instance, if not provided, it will be58 read/created from the simulation files under the directory59 :returns: list of dictionaries { 'domain':_, 'server':_ }60 """61 entryPoints = None62 # Generate where the requests will be launched63 mdCfgReader = MDCR.MultiDomainConfReader(self.__simName)64 mdProperties = mdCfgReader.readConfFields()65 entryPointsPath = configPath + '/' + self.__simName +\66 '/entryPoints.json'67 # Retrieve the multiDomain instance68 md = None69 if not multiDomain:70 md = mdCfgReader.readDumped()71 if not md:72 md = mdCfgReader.read()73 else:74 md = multiDomain75 ############76 # Generate #77 ############78 if not os.path.exists(entryPointsPath):79 # Generate NS request entry points 80 nsEntryPoints = []81 for _ in range(requests):82 domain = random.randint(0, mdProperties['domains'] - 1)83 serverDicts = md.getServers(domain)84 servers = serverDicts.keys()85 server = servers[random.randint(0, len(servers) - 1)]86 nsEntryPoints.append({ "domain": domain, "server": server })87 # Dump them88 with open(entryPointsPath, 'w') as entryOut:89 json.dump(nsEntryPoints, entryOut)90 ########91 # Read #92 ########93 else:94 with open(entryPointsPath) as f:95 nsEntryPoints = json.load(f)96 return nsEntryPoints97 def read(self, multiDomain=None):98 """Reads the configuration file to generate the NS bunch99 based on the config file of the simulation. After generating the100 NS bunch, it is stored as a list of GML files with its properties.101 :multiDomain: multiDomain on top of which the the NS bunch are mapped102 :returns: [list of NS instances, list of entry points]103 [None, None] in case of error104 """105 nsBunchProperties = self.__readConfig()106 if not nsBunchProperties:107 return None, None108 nsBunch = NSG.NSgenerator.genNsBunch(109 nsBunchProperties['numNs'],110 nsBunchProperties['bwTh'],111 nsBunchProperties['delayTh'],112 nsBunchProperties['memoryTh'],113 nsBunchProperties['diskTh'],114 nsBunchProperties['cpuTh'],115 nsBunchProperties['splits'],116 nsBunchProperties['splitWidth'],117 nsBunchProperties['branches'],118 nsBunchProperties['vnfs'])119 NSG.NSgenerator.writeNsBunch(nsBunch, 'nsBunch',120 baseAbsPath=configPath + '/' + self.__simName)121 entryPoints = self.__genEntryPoints(nsBunchProperties['numNs'],122 multiDomain=multiDomain)...

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