Testing a Python Model Object

I am writing an interface that will be used by two applications. This interface should use some DoSomethingRequest and DoSomethingResponse classes for communication.

Is there any library that does some model checking like Django Model ?

I basically want to say something like:
Object A must have a text property of type str (), a number property of type int (), a property of items of type list (). Dry way.

I am looking for something like the following or better:

 class MyEmbeddedModelClass(EmbeddedModel): text = TextField(required = True) class MyModel(Model): text = TextField(required = True) number = IntField(default = 0) items = ListField(EmbeddedModel) a = MyModel() a.text = "aaaa" a.number = 1 a.items = [ MyEmbeddedModelClass("bbbb"), MyEmbeddedModelClass("cccc"), MyEmbeddedModelClass("dddd") ] a.validate() 

I know that I can write on my own, but I would prefer to use the library if it is available, but I'm a little new to this.

+6
source share
3 answers

If you want to use interfaces or use design behind a contract, then you probably need the zope.interface library. Despite the name, which reflects its origin in Zope, it is not actually attached to this structure at all and can be used externally.

+3
source

I think decorators can be used for this. check this link

Combining Descriptors with Class Decorators to Validate

For a different approach check out duck typing

+2
source

Since python is dynamic, the convention should require that the object behave as an instance of a specific class, rather than applying a specific type.

Somewhere in your code, preferably at the moment when you need to access these properties, but as soon as possible approve that the object has these properties and further claim that these properties are what you expect from them.

This throws an AssertionError exception if the object is o , regardless of type, if it does not have the attribute "someattribute":

 assert(hasattr(o, 'someattribute')) 

Also, if o.someattribute not a string:

 assert(isinstance(o.someattribute, basestring)) 
0
source

Source: https://habr.com/ru/post/899222/


All Articles