|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# SPDX-License-Identifier: BSD-3-Clause-Clear |
| 3 | +# Copyright (c) 2019, The Numerical Algorithms Group, Ltd. All rights reserved. |
| 4 | + |
| 5 | +__all__ = ["SimpleAsserter", "ListofStrAsserter"] |
| 6 | + |
| 7 | + |
| 8 | +class BaseAsserter: |
| 9 | + """Parent class for type asserter objects |
| 10 | +
|
| 11 | + Asserter classes provide a callable which can be used to assert the validity of an |
| 12 | + object. |
| 13 | +
|
| 14 | + Subclasses should implement a check_type function returning true/false as needed. |
| 15 | + """ |
| 16 | + |
| 17 | + _expected = None |
| 18 | + |
| 19 | + def __call__(self, testobj): |
| 20 | + if not self.check_type(testobj): |
| 21 | + raise TypeError( |
| 22 | + "Expected {} not {}".format(self._expected, testobj.__class__.__name__) |
| 23 | + ) |
| 24 | + return True |
| 25 | + |
| 26 | + def check_type(self, testobj): |
| 27 | + """Return true if object is valid |
| 28 | +
|
| 29 | + Parameters |
| 30 | + ---------- |
| 31 | + testobj: object |
| 32 | + Object to be validated. |
| 33 | + """ |
| 34 | + raise NotImplementedError() |
| 35 | + |
| 36 | + |
| 37 | +class SimpleAsserter(BaseAsserter): |
| 38 | + """Assert that an object is of a given type |
| 39 | +
|
| 40 | + Provides a callable object which asserts the provided object is of the required type. |
| 41 | + """ |
| 42 | + |
| 43 | + def __init__(self, assert_class): |
| 44 | + """Define class to be validated |
| 45 | +
|
| 46 | + Parameters |
| 47 | + ---------- |
| 48 | + assert_class: class |
| 49 | + Reference class to be compared to. |
| 50 | + """ |
| 51 | + self._assert_cls = assert_class |
| 52 | + self._expected = assert_class.__name__ |
| 53 | + |
| 54 | + def check_type(self, testobj): |
| 55 | + if isinstance(testobj, self._assert_cls): |
| 56 | + return True |
| 57 | + |
| 58 | + |
| 59 | +class ListofStrAsserter(BaseAsserter): |
| 60 | + """Assert that an object is a list of strings |
| 61 | +
|
| 62 | + Provides a callable object which asserts a provided object is a list of strings. |
| 63 | + """ |
| 64 | + |
| 65 | + _expected = "list of str" |
| 66 | + |
| 67 | + def check_type(self, testobj): |
| 68 | + if isinstance(testobj, list) and all(isinstance(x, str) for x in testobj): |
| 69 | + return True |
0 commit comments