Easy way to fake freely defined Python voice recorder objects

Is there an easy way to trick freely defined dict objects in Python? For example, how can I easily express that given dict input , I want to check if each value in it corresponds to a certain meta-definition, for example, minimum and maximum values, lengths and types?

The ability to do this can come in handy, for example, when writing tests.

In mock ( unittest.mock in Python versions 3.3+), you can specify that the value can be ANY , as in

 >>> mock = Mock(return_value=None) >>> mock('foo', bar=object()) >>> mock.assert_called_once_with('foo', bar=ANY) 

However, what if bar above should be a dictate-like object, for example

 >>> {'baz': <an integer between -3 and 14>, 'qux': <'yes' or 'no'>} 
+6
source share
1 answer

I actually wrote AnyValid , a minimal library that uses a lot of the work implemented in formencode and unittest.mock to handle such cases.

For example, testing a dict as described above can be expressed as

 >>> from mock import Mock >>> from any_valid import AnyValid, Int, OneOf >>> valid_bar = { ... 'baz': AnyValid(Int(min=-3, max=14)), ... 'qux': AnyValid(OneOf(['yes', 'no'])), ... } >>> mock = Mock(return_value=None) >>> mock('foo', bar={'baz': 4, 'qux': 'yes'}) >>> mock.assert_called_once_with('foo', bar=valid_bar) >>> 

Since AnyValid can accept any validator from a large set of validators in formencode, many other conditions can be specified in a similarly expressive way.

+5
source

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


All Articles