├── .gitignore ├── .travis.yml ├── LICENSE ├── Makefile ├── README.md ├── docs ├── core │ ├── model.md │ ├── object.md │ └── validator.md └── validators │ ├── bool_validator.md │ ├── integer_validator.md │ ├── nested_validator.md │ └── range_validator.md ├── rebase ├── __init__.py ├── core │ ├── __init__.py │ ├── model.py │ ├── object.py │ └── validator.py └── validators │ ├── __init__.py │ ├── alnum_validator.py │ ├── bool_validator.py │ ├── integer_validator.py │ ├── nested_validator.py │ ├── range_validator.py │ └── string_validator.py ├── setup.py └── tests ├── __init__.py └── core ├── test_model.py ├── test_object.py └── test_validator.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | .pytest_cache/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | 58 | # Flask stuff: 59 | instance/ 60 | .webassets-cache 61 | 62 | # Scrapy stuff: 63 | .scrapy 64 | 65 | # Sphinx documentation 66 | docs/_build/ 67 | 68 | # PyBuilder 69 | target/ 70 | 71 | # Jupyter Notebook 72 | .ipynb_checkpoints 73 | 74 | # pyenv 75 | .python-version 76 | 77 | # celery beat schedule file 78 | celerybeat-schedule 79 | 80 | # SageMath parsed files 81 | *.sage.py 82 | 83 | # dotenv 84 | .env 85 | 86 | # virtualenv 87 | .venv 88 | venv/ 89 | ENV/ 90 | 91 | # Spyder project settings 92 | .spyderproject 93 | .spyproject 94 | 95 | # Rope project settings 96 | .ropeproject 97 | 98 | # mkdocs documentation 99 | /site 100 | 101 | # mypy 102 | .mypy_cache/ 103 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - 3.6 4 | install: 5 | - pip install pipenv 6 | - make env 7 | - make setup 8 | script: 9 | - make test 10 | deploy: 11 | provider: pypi 12 | user: locustv2 13 | password: 14 | secure: Ba+I6/O1qKM5Y2FoI2nmAft7WJQ88NouP5FH3nVSAZbJOyRx5R5O9NFSvhFbzfjfHdiJJHgxdr39CcdWnsmk6hEifSYyg06I+Kbwdso18eusIGcoOzuTm9chC9y76aYYt7zL6dzBoI9hrQg6dSqjbgAaVPqFzyyGKkObP7EvND0UsaLn97oQniaLT5hWISfPJSyUwbX4UDM6Mbd5yWJoR65LMECeIsYGgMPQA5bBM+4SWqHaCF5NOchFjIcyZBG2YyRJjS/j3+/m8TiyTC8c0zoZ3bU+D6dE0vMDlZlTG64Z3ud9pk84PHIykXCbhBIKW84UhoIUPl5xRf198yrgRhmTTLs+XVS64SuvPJZ2e8eLnvokuFlQiKBqp2exejlV9VgIHXbCIMkytwyvPhjZHy/ia9df8DH4dLK0/fHr0nGwM3to3X3iXhxNV9Cf8+f+KAMT/aURgWjYXLQuAwSeQmcuQE5ggf5XFNO0V7LEhE5mthNaNlu5jY9apUW8aezjMnjDyNJNDnL1hP69cJyfu9vStt/Fp40myKdLN9xecImJjxj9bE7yN6mDbPmJot9yAVzzUWJl5opK2XKkE3+/Wzl4JKLimZ0Mzkklk1/WCCn677/eY9yZ/DJ2RtcBQt2af4i7k/zE9vXP9/JBZ0+F4JlgDbj4ZlBiMcrPZ1XXdjw= 15 | distributions: sdist bdist_wheel 16 | on: 17 | tags: true 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | env: 2 | pipenv --venv || pipenv --python 3.6 3 | 4 | activate: 5 | pipenv shell 6 | 7 | setup: 8 | pipenv install -e . --skip-lock --ignore-pipfile -v 9 | 10 | test: 11 | pipenv run python setup.py test 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rebase [![Build Status](https://travis-ci.org/trivago/rebase.svg?branch=master)](https://travis-ci.org/trivago/rebase) 2 | 3 | 4 | ## What is it? 5 | Rebase is a small library consisting of powerful reusable components aimed at making your Data Layer more robust. With the changes of how data is being stored in databases, it is becoming very challenging to validate data specially in NoSQL databases. 6 | 7 | Rebase is designed in such a way that it is easier to manipulate the data and project them in different views. 8 | 9 | 10 | ## Challenges that lead to this idea 11 | Working daily with data having different structures becomes a pain eventually. Sometimes you have to adapt or map an object to another format or apply some filters to part of the data. This occurs very often when have data coming from different sources and want to conform them. 12 | 13 | ## Getting Started 14 | 15 | ### Installation 16 | Install via [pip](http://www.pip-installer.org/) 17 | ```bash 18 | $ pip install rebase 19 | ``` 20 | 21 | ## Documentation 22 | 23 | ### core 24 | - [rebase.core.Object](docs/core/object.md) 25 | - [rebase.core.Model](docs/core/model.md) 26 | - [rebase.core.Validator](docs/core/validator.md) 27 | ### validators 28 | - [rebase.validators.BoolValidator](docs/validators/bool_validator.md) 29 | - [rebase.validators.IntegerValidator](docs/validators/integer_validator.md) 30 | - [rebase.validators.NestedValidator](docs/validators/nested_validator.md) 31 | - [rebase.validators.RangeValidator](docs/validators/range_validator.md) 32 | -------------------------------------------------------------------------------- /docs/core/model.md: -------------------------------------------------------------------------------- 1 | # [`rebase.core.Model`](/rebase/core/model.py) 2 | 3 | The `rebase.core.Model` represents an entity which can have a set of rules to be validated against. A model can have different scenarios each having different set of validation rules. 4 | 5 | After validation has been triggered the model receives the errors from the validators if the validation failed for a specific rule. Context and scenarios can also be used to have different projection of the attributes. 6 | 7 | ## Documentation 8 | 9 | 10 | ### class rebase.core.Object 11 | 12 | 13 | #### Public Properties 14 | 15 | | Property | Type | Description | Defined By | 16 | |-----------|---------------|--------------------------------------------------------------------|----------------------------------------| 17 | | attributes | dictionary {string: Any} | The object attributes that can be publicly accessed and modified | [`rebase.core.Object`](#rebasecoreobject) | 18 | | classname | string | The fully qualified name of the class | [`rebase.core.Object`](#rebasecoreobject) | 19 | 20 | 21 | #### Public Methods 22 | 23 | 24 | ## How to use `rebase.core.Model`? 25 | -------------------------------------------------------------------------------- /docs/core/object.md: -------------------------------------------------------------------------------- 1 | # [`rebase.core.Object`](/rebase/core/object.py) 2 | 3 | The `rebase.core.Object` is an improved version of the base python `object`. It offers several generic functions that you can use to build your objects. It is the core of rebase and all the rebase components are built on it. 4 | 5 | It offers the ability to declare public and private properties as well as introducing basic types on the properties. However the way to declare arguments within a class is different from what you normally do in python. 6 | 7 | Depending on the arguments that you pass to the constructor, properties will be created dynamically. 8 | 9 | 10 | ## Documentation 11 | 12 | 13 | ### class rebase.core.Object 14 | 15 | 16 | #### Public Properties 17 | 18 | | Property | Type | Description | Defined By | 19 | |-----------|---------------|--------------------------------------------------------------------|----------------------------------------| 20 | | attributes | dictionary {string: Any} | The object attributes that can be publicly accessed and modified | [`rebase.core.Object`](#rebasecoreobject) | 21 | | classname | string | The fully qualified name of the class | [`rebase.core.Object`](#rebasecoreobject) | 22 | 23 | 24 | #### Public Methods 25 | 26 | | Method | Type | Description | Defined By | 27 | |-----------|---------------|--------------------------------------------------------------------|----------------------------------------| 28 | | `__init__(self, **kwargs)` | void | Initialize the object based on arguments passed. If `properties()` method is not overridden, all arguments will be a property of the object. | [`rebase.core.Object`](#rebasecoreobject) | 29 | | `__getattr__(self, attr_name: str) -> Any` | Any | Returns the value of the specified attribute. | [`rebase.core.Object`](#rebasecoreobject) | 30 | | `__setattr__(self, attr_name: str, value: Any)` | void | Sets the value of the specified attribute. | [`rebase.core.Object`](#rebasecoreobject) | 31 | | `__str__(self) -> str` | string | Returns a representation of the object in json. | [`rebase.core.Object`](#rebasecoreobject) | 32 | | `__repr__(self) -> str` | string | Returns a representation of the object with initialized arguments. | [`rebase.core.Object`](#rebasecoreobject) | 33 | | `get(self, *attrs) -> Dict[str, Any]` | dictionary {string: Any} | Returns all the object attributesm specified in the arguments, if they exist | [`rebase.core.Object`](#rebasecoreobject) | 34 | | `get_id(self)` | string | Returns a unique uuid4. | [`rebase.core.Object`](#rebasecoreobject) | 35 | | `properties(self) -> Dict[str, Any]` | dictionary {string: Any} | Returns the mapping of properties to argument of the object. | [`rebase.core.Object`](#rebasecoreobject) | 36 | 37 | 38 | ## How to use `rebase.core.Object`? 39 | - [Basic usage without inheriting](#basic-usage-without-inheriting) 40 | - [Extending and customizing an object](#extending-and-customizing-an-object) 41 | 42 | 43 | ### Basic usage without inheriting 44 | You can create dynamic objects and use the arguments passed as properties. 45 | 46 | ```py 47 | from rebase.core import Object 48 | 49 | obj = Object(name='Paul', age=35, location='France') 50 | 51 | print(obj.name) # Paul 52 | print(obj.age) # 35 53 | print(obj.location) # France 54 | print(obj.attributes) # {'name': 'Paul', 'age': 35, 'location': 'France'} 55 | print(obj.get('name', 'age')) # {'name': 'Paul', 'age': 35} 56 | ``` 57 | 58 | ### Extending and customizing an object 59 | You can also extend the object and create customized objects with specific properties. Mappings of the properties to the constructor arguments can be done easily and types of the property can be enforced. 60 | 61 | ```py 62 | from rebase.core import Object 63 | 64 | class Person(Object): 65 | def properties(self): 66 | return { 67 | 'firstname': 'name', 68 | 'age': ('age', int), 69 | 'gender': ('gender', lambda x: int(x=='Male')), 70 | 'city': 'location.city', 71 | 'country': ('location.country', lambda x: x.upper()), 72 | } 73 | 74 | 75 | obj = Person( 76 | name='Paul', 77 | age='35', 78 | gender="Male", 79 | location=dict( 80 | city='Paris', 81 | country='France' 82 | ), 83 | is_admin=False, 84 | ) 85 | 86 | print(obj.attributes) 87 | # {'firstname': 'Paul', 'age': 35, 'gender': 1, 'city': 'Paris', 'Country': France} 88 | ``` 89 | -------------------------------------------------------------------------------- /docs/core/validator.md: -------------------------------------------------------------------------------- 1 | # [`rebase.core.Validator`](/rebase/core/validator.py) 2 | -------------------------------------------------------------------------------- /docs/validators/bool_validator.md: -------------------------------------------------------------------------------- 1 | # [`rebase.validators.BoolValidator`](/rebase/validators/bool_validator.py) 2 | -------------------------------------------------------------------------------- /docs/validators/integer_validator.md: -------------------------------------------------------------------------------- 1 | # [`rebase.validators.IntegerValidator`](/rebase/validators/integer_validator.py) 2 | -------------------------------------------------------------------------------- /docs/validators/nested_validator.md: -------------------------------------------------------------------------------- 1 | # [`rebase.validators.NestedValidator`](/rebase/validators/nested_validator.py) 2 | -------------------------------------------------------------------------------- /docs/validators/range_validator.md: -------------------------------------------------------------------------------- 1 | # [`rebase.validators.RangeValidator`](/rebase/validators/range_validator.py) 2 | -------------------------------------------------------------------------------- /rebase/__init__.py: -------------------------------------------------------------------------------- 1 | name = "rebase" 2 | -------------------------------------------------------------------------------- /rebase/core/__init__.py: -------------------------------------------------------------------------------- 1 | from .object import Object 2 | from .validator import Validator 3 | from .model import Model 4 | -------------------------------------------------------------------------------- /rebase/core/model.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | from typing import Any, Dict, List 12 | from rebase.core import Object, Validator 13 | 14 | 15 | class Model(Object): 16 | def __init__(self, context=None, **attributes): 17 | self._errors = {} 18 | self._context = context 19 | super().__init__(**attributes) 20 | 21 | def _debug(self) -> Dict[str, Any]: 22 | return { 23 | **super()._debug(), 24 | **{ 25 | '_errors': self._errors, 26 | '_context': self._context 27 | } 28 | } 29 | 30 | def _properties(self) -> List[str]: 31 | return [*super()._properties(), '_errors', '_context'] 32 | 33 | @property 34 | def attributes(self) -> Dict[str, Any]: 35 | context_attributes = self.scenarios().get(self._context) 36 | return super().attributes if not context_attributes else { 37 | k: v 38 | for k, v in super().attributes.items() 39 | if context_attributes and k in context_attributes 40 | } 41 | 42 | def rules(self) -> Dict[str, List[Validator]]: 43 | return {} 44 | 45 | def scenarios(self) -> Dict[str, List[str]]: 46 | return {} 47 | 48 | def validate(self, attribute = None) -> bool: 49 | is_valid = True 50 | if not attribute: 51 | self._errors.clear() 52 | else: 53 | self._errors.update({attribute: []}) 54 | 55 | for attr, ruleset in self.rules().items(): 56 | if attribute and attr != attribute: 57 | continue 58 | for rule in ruleset: 59 | value = getattr(self, attr, None) 60 | if rule.required and value is None: 61 | self.add_errors(attr, [f'`{attr}` is a required field.']) 62 | is_valid = False 63 | continue 64 | is_valid &= rule.validate(value) 65 | self.add_errors(attr, rule.errors) 66 | 67 | return is_valid 68 | 69 | def add_errors(self, attribute, messages): 70 | attribute_errors = self._errors.get(attribute, []) 71 | self._errors[attribute] = attribute_errors + messages 72 | 73 | def get_errors(self, attribute=None) -> Dict[str, List[str]]: 74 | return self._errors.get(attribute) if attribute else self._errors 75 | 76 | def get_context(self): 77 | return self._context 78 | 79 | def set_context(self, value): 80 | self._context = value 81 | -------------------------------------------------------------------------------- /rebase/core/object.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | import uuid 12 | from typing import Any, Dict, List 13 | import logging 14 | import simplejson as json 15 | 16 | 17 | class Object(object): 18 | def __dir__(self): 19 | """Return a list of attributes for the class. 20 | 21 | Returns: a list of attributes for the class. 22 | 23 | """ 24 | return [*self._attributes.keys(), *['attributes', 'classname']] 25 | 26 | def __init__(self, **kwargs): 27 | """Initialize the object with the given attributes. 28 | 29 | If this method is overridden in the child, the parent implementation 30 | should be called in order to properly assign attributes. 31 | 32 | By default attributes are assigned dynamically to the object. But to 33 | have more control in child classes (such as remapping), it is 34 | recommended to override the `Object.properties()` method. 35 | 36 | Args: 37 | **kwargs: Arbitrary keyword argument which by default becomes an 38 | attribute of the object unless specified otherwise in 39 | `Object.properties()`. 40 | ```python 41 | print [i*2 for i in range(1,10)] 42 | ``` 43 | 44 | """ 45 | self._raw_attributes = kwargs 46 | self._attributes = {} 47 | self._id = None 48 | self._init_attributes() 49 | 50 | def __getattr__(self, attr_name: str) -> Any: 51 | """Return the value of an object attribute. 52 | 53 | Do not call this method directly as it is a python magic function that 54 | will be implicitly called when executing `value = object.attribute` or 55 | `value = getattr(object, 'attribute')` 56 | 57 | Args: 58 | attr_name (string): the attribute name 59 | 60 | Returns: 61 | Any: the value of the attribute 62 | 63 | Raises: 64 | AttributeError: If attribute is undefinied in `Object.properties()` 65 | 66 | """ 67 | if attr_name in self._properties(): 68 | return super().__getattr__(attr_name) 69 | elif attr_name not in self.properties(): 70 | raise AttributeError( 71 | f'Getting unknown property: `{self.classname}.{attr_name}`.') 72 | return self._attributes.get(attr_name) 73 | 74 | def __setattr__(self, attr_name: str, value: Any): 75 | """Set the value of an object attribute. 76 | 77 | Do not call this method directly as it is a python magic function that 78 | will be implicitly called when executing `object.attribute = value` or 79 | `setattr(object, 'attribute', value)` 80 | 81 | Args: 82 | attr_name (string): the attribute name 83 | value (Any): the attribute value 84 | 85 | Raises: 86 | AttributeError: If attribute is undefinied in `Object.properties()` 87 | 88 | """ 89 | if attr_name in self._properties(): 90 | super().__setattr__(attr_name, value) 91 | elif attr_name not in self.properties(): 92 | raise AttributeError( 93 | f'Setting unknown property: `{self.classname}.{attr_name}`.') 94 | else: 95 | attr = self.properties().get(attr_name) 96 | if isinstance(attr, tuple) and value is not None: 97 | k, v = attr 98 | if type(value) != v: 99 | raise AttributeError( 100 | f'`Value for {self.classname}.{attr_name}` should be of type {v}; {type(value)} provided.') 101 | 102 | self._attributes.update({attr_name: value}) 103 | 104 | def __str__(self) -> str: 105 | """Return a string representation of the object in json. 106 | 107 | Returns: a string representation of the object in json format. 108 | 109 | """ 110 | return json.dumps(self._debug(), use_decimal=True) 111 | 112 | def __repr__(self) -> str: 113 | """Return the representation of the object at creation. 114 | 115 | Returns: 116 | string: the representation with constructor arguments 117 | 118 | """ 119 | return '{classname}(**{args})'.format( 120 | classname=self.classname, 121 | args=self._raw_attributes 122 | ) 123 | 124 | def _debug(self) -> Dict[str, Any]: 125 | return { 126 | '_id': self.get_id(), 127 | 'attributes': self.attributes 128 | } 129 | 130 | def _enforce_data_type(self, data: Any, data_type: type) -> Any: 131 | try: 132 | if data is not None: 133 | if isinstance(data_type, type) and isinstance(data_type(), Object): 134 | return data_type(**data) 135 | elif data_type in (bool, str, int, float, complex, list, tuple, range, set, dict) or callable(data_type): 136 | return data_type(data) 137 | except TypeError: 138 | return data 139 | 140 | return data 141 | 142 | def _init_attributes(self): 143 | """Perform the mapping of attributes based `Object.properties()`. 144 | 145 | Returns: 146 | void 147 | 148 | """ 149 | for k, v in self.properties().items(): 150 | if isinstance(v, str): 151 | logging.debug('Key: %s is being parsed as `str` with value: %s', k, v) 152 | self._attributes.setdefault( 153 | k, self._get_attr_recurse(v, self._raw_attributes)) 154 | elif isinstance(v, tuple): 155 | logging.debug('Key: %s is being parsed as `tuple` with value: %s', k, v) 156 | attribute, data_type = v 157 | data = None 158 | if attribute and isinstance(attribute, str): 159 | data = self._get_attr_recurse( 160 | attribute, self._raw_attributes) 161 | elif callable(attribute): 162 | data = attribute() 163 | 164 | self._attributes.setdefault(k, 165 | self._enforce_data_type( 166 | data, data_type)) 167 | elif isinstance(v, type) and isinstance(v(), Object): 168 | logging.debug('Key: %s is being parsed as `rebase.core.Object` with value: %s', k, v) 169 | self._attributes.setdefault(k, v(**self._raw_attributes)) 170 | elif callable(v): 171 | logging.debug('Key: %s is being parsed as `callable` with value: %s', k, v) 172 | self._attributes.setdefault(k, v()) 173 | elif k in self._raw_attributes: 174 | logging.debug('Key: %s is being parsed as `raw_attributes` with value: %s', k, v) 175 | self._attributes.setdefault(k, self._raw_attributes.get(k)) 176 | else: 177 | logging.debug('Key: %s is being parsed as `raw_attributes` with value: %s', k, v) 178 | self._attributes.setdefault(k, self._raw_attributes.get(k, v)) 179 | 180 | def _get_attr_recurse(self, attr, obj, idx=0): 181 | if isinstance(obj, Object): 182 | return self._get_attr_recurse(attr, obj.attributes, idx) 183 | elif obj is None: 184 | return None 185 | 186 | attr_list = attr.split('.') 187 | key = attr_list.pop(idx) 188 | if key not in obj: 189 | return None 190 | 191 | if len(attr_list) == idx: 192 | return obj.get(key) 193 | else: 194 | return self._get_attr_recurse(attr, obj.get(key), idx+1) 195 | 196 | def _properties(self) -> List[str]: 197 | return ['_id', '_attributes', '_raw_attributes'] 198 | 199 | @property 200 | def attributes(self) -> Dict[str, Any]: 201 | """Return the attributes of the object based on `Object.properties()`. 202 | 203 | Return: 204 | dict: a dictionary of the attributes of the object 205 | """ 206 | return self.get(*self._attributes) 207 | 208 | @property 209 | def classname(self) -> str: 210 | """Return the qualified name of this class. 211 | 212 | Returns: 213 | string: the qualified name of this class 214 | 215 | 216 | """ 217 | return self.__class__.__name__ 218 | 219 | def get(self, *attrs) -> Dict[str, Any]: 220 | """Return a dict of the attribute names passed as arguments. 221 | 222 | Args: 223 | attrs (list): comma separated name of attributes for the object 224 | 225 | Returns: 226 | dict: the attributes of the object if set 227 | 228 | """ 229 | return { 230 | k: v.attributes 231 | if isinstance(v, Object) else [ 232 | x.attributes 233 | if isinstance(x, Object) else x 234 | for x in v 235 | ] 236 | if isinstance(v, list) else { 237 | x: y.attributes 238 | if isinstance(y, Object) else y 239 | for x, y in v.items() 240 | } 241 | if isinstance(v, dict) else { 242 | x.get_id(): x.attributes 243 | for x in v 244 | } 245 | if isinstance(v, set) else v 246 | for k, v in self._attributes.items() if k in attrs 247 | } 248 | 249 | def get_id(self): 250 | """Generate and return the unique id of the object. 251 | 252 | Returns: 253 | string: the unique id generated by uuid 254 | 255 | """ 256 | if not self._id: 257 | self._id = str(uuid.uuid4()) 258 | return self._id 259 | 260 | def properties(self) -> Dict[str, Any]: 261 | """Return the mapping of properties passed to the constructor. 262 | 263 | This method can be overridden if you want more customised _properties 264 | and do advanced mapping of your attributes. 265 | 266 | Returns: 267 | dict: the mapped properties passed to constructor 268 | 269 | """ 270 | return self._raw_attributes.get('properties') or { 271 | k: k for k, v in self._raw_attributes.items() 272 | } 273 | -------------------------------------------------------------------------------- /rebase/core/validator.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | from rebase.core import Object 12 | 13 | 14 | class Validator(Object): 15 | def __init__(self, **attributes): 16 | super().__init__(**attributes) 17 | 18 | def properties(self): 19 | return { 20 | 'errors': [], 21 | 'required': False, 22 | 'message': lambda: f'{{value}} failed to comply with {self.classname} rules.' 23 | } 24 | 25 | def validate(self, value): 26 | is_valid = True 27 | self.errors.clear() 28 | 29 | for validator in self.depends_on(): 30 | is_valid &= validator.validate(value) 31 | self.errors += validator.errors 32 | 33 | return is_valid 34 | 35 | def depends_on(self): 36 | return {} 37 | -------------------------------------------------------------------------------- /rebase/validators/__init__.py: -------------------------------------------------------------------------------- 1 | from .bool_validator import BoolValidator 2 | from .integer_validator import IntegerValidator 3 | from .nested_validator import NestedValidator 4 | from .range_validator import RangeValidator 5 | from .string_validator import StringValidator 6 | from .alnum_validator import AlnumValidator 7 | -------------------------------------------------------------------------------- /rebase/validators/alnum_validator.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | from rebase.core import Validator 12 | from rebase.validators import StringValidator 13 | 14 | 15 | class AlnumValidator(Validator): 16 | def properties(self): 17 | return { 18 | **super().properties(), 19 | 'message': lambda: '`{value}` is not a valid alphanumeric string.' 20 | } 21 | 22 | def validate(self, value): 23 | if not super().validate(value): 24 | return False 25 | 26 | is_valid = True 27 | 28 | if not value.isalnum(): 29 | self.errors.append(self.message.format(value=value)) 30 | is_valid &= False 31 | 32 | return is_valid 33 | 34 | def depends_on(self): 35 | return {StringValidator(required=self.required)} 36 | -------------------------------------------------------------------------------- /rebase/validators/bool_validator.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | from rebase.core import Validator 12 | 13 | 14 | class BoolValidator(Validator): 15 | def properties(self): 16 | return { 17 | **super().properties(), 18 | 'message': lambda: '`{value}` is not a boolean' 19 | } 20 | 21 | def validate(self, value): 22 | if not super().validate(value): 23 | return False 24 | 25 | is_valid = True 26 | 27 | if type(value) is not bool: 28 | self.errors.append(self.message.format(value=str(value))) 29 | is_valid &= False 30 | 31 | return is_valid 32 | -------------------------------------------------------------------------------- /rebase/validators/integer_validator.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | from rebase.core import Validator 12 | 13 | 14 | class IntegerValidator(Validator): 15 | def properties(self): 16 | return { 17 | **super().properties(), 18 | 'message': lambda: '`{value}` is not an integer' 19 | } 20 | 21 | def validate(self, value): 22 | if not super().validate(value): 23 | return False 24 | 25 | is_valid = True 26 | 27 | if type(value) is not int: 28 | self.errors.append(self.message.format(value=value)) 29 | is_valid &= False 30 | 31 | return is_valid 32 | -------------------------------------------------------------------------------- /rebase/validators/nested_validator.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | from rebase.core import Model, Validator 12 | 13 | 14 | class NestedValidator(Validator): 15 | def properties(self): 16 | return { 17 | **super().properties(), 18 | 'required': True, 19 | } 20 | 21 | def validate(self, value): 22 | if not super().validate(value): 23 | return False 24 | 25 | is_valid = True 26 | 27 | if isinstance(value, Model) and not value.validate(): 28 | is_valid = False 29 | self.errors.append(value.get_errors()) 30 | elif isinstance(value, dict): 31 | for k, v in value.items(): 32 | if isinstance(v, Model) and not v.validate(): 33 | is_valid = False 34 | self.errors.append({k: v.get_errors()}) 35 | elif isinstance(value, list) or isinstance(value, set): 36 | for v in value: 37 | if isinstance(v, Model) and not v.validate(): 38 | is_valid = False 39 | self.errors.append({v.get_id(): v.get_errors()}) 40 | 41 | return is_valid 42 | -------------------------------------------------------------------------------- /rebase/validators/range_validator.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | from rebase.core import Validator 12 | from rebase.validators import IntegerValidator 13 | 14 | 15 | class RangeValidator(Validator): 16 | def properties(self): 17 | return { 18 | **super().properties(), 19 | 'min': None, 20 | 'max': None, 21 | 'message': lambda: '{value} is not within the range {min} and {max}' 22 | } 23 | 24 | def validate(self, value): 25 | if not super().validate(value): 26 | return False 27 | 28 | is_valid = True 29 | 30 | if not (int(value) >= self.min and int(value) <= self.max): 31 | self.errors.append( 32 | self.message.format( 33 | value=str(value), 34 | min=str(self.min), 35 | max=str(self.max) 36 | ) 37 | ) 38 | is_valid &= False 39 | 40 | return is_valid 41 | 42 | def depends_on(self): 43 | return {IntegerValidator(required=self.required)} 44 | -------------------------------------------------------------------------------- /rebase/validators/string_validator.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.2 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | from rebase.core import Validator 12 | 13 | 14 | class StringValidator(Validator): 15 | def properties(self): 16 | return { 17 | **super().properties(), 18 | 'message': lambda: '`{value}` is not a valid string' 19 | } 20 | 21 | def validate(self, value): 22 | if not super().validate(value): 23 | return False 24 | 25 | is_valid = True 26 | 27 | if type(value) is not str: 28 | self.errors.append(self.message.format(value=value)) 29 | is_valid &= False 30 | 31 | return is_valid 32 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from setuptools import find_packages, setup 4 | from setuptools.command.test import test as TestCommand 5 | 6 | 7 | class Pytest(TestCommand): 8 | def initialize_options(self): 9 | TestCommand.initialize_options(self) 10 | self.pytest_args = [ 11 | '--cov=rebase', '--cov-report', 'term-missing', '--fulltrace', 12 | '-vv', '-s' 13 | ] 14 | 15 | def run_tests(self): 16 | #import here, cause outside the eggs aren't loaded 17 | import pytest 18 | errno = pytest.main(self.pytest_args) 19 | sys.exit(errno) 20 | 21 | 22 | setup( 23 | name='rebase', 24 | version='1.2.2', 25 | python_requires='>=3.6', 26 | author="Yuv Joodhisty", 27 | author_email="locustv2@gmail.com", 28 | maintainer="Yuv Joodhisty", 29 | maintainer_email="locustv2@gmail.com", 30 | packages=find_packages(exclude=['tests']), 31 | include_package_data=True, 32 | long_description=open('README.md').read(), 33 | long_description_content_type="text/markdown", 34 | use_scm_version=True, 35 | setup_requires=['setuptools_scm'], 36 | install_requires=[ 37 | 'simplejson', 38 | ], 39 | tests_require=['pytest-cov', 'pytest', 'mock'], 40 | cmdclass={'test': Pytest}, 41 | test_suite='tests', 42 | classifiers=( 43 | "Programming Language :: Python :: 3", 44 | "Operating System :: OS Independent", 45 | ) 46 | ) 47 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/trivago/rebase/e116c08ae79f46d63df711d224a4062d4e97469f/tests/__init__.py -------------------------------------------------------------------------------- /tests/core/test_model.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.0 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | import unittest 12 | from unittest import mock 13 | from rebase.core import Model 14 | from rebase.validators import RangeValidator 15 | 16 | 17 | @mock.patch.multiple( 18 | Model, 19 | scenarios=mock.Mock( 20 | return_value={ 21 | 'personal': ['name', 'age', 'gender'] 22 | } 23 | ), 24 | rules=mock.Mock( 25 | return_value={ 26 | 'age': [RangeValidator(min=20, max=30)] 27 | } 28 | ), 29 | properties=mock.Mock( 30 | return_value={ 31 | 'name': 'name', 32 | 'age': 'age', 33 | 'gender': ('gender', lambda x: int(x == 'Male')), 34 | 'location': ('location', lambda x: x.upper()), 35 | } 36 | ) 37 | ) 38 | class TestModel(unittest.TestCase): 39 | def setUp(self): 40 | self.model = Model( 41 | context='personal', 42 | name='Paul', 43 | age=35, 44 | gender="Male", 45 | location="Germany") 46 | 47 | def test_model_scenario(self): 48 | self.assertIn('name', self.model.attributes) 49 | self.assertIn('age', self.model.attributes) 50 | self.assertIn('gender', self.model.attributes) 51 | self.assertNotIn('location', self.model.attributes) 52 | 53 | def test_model_rules(self): 54 | self.assertFalse(self.model.validate()) 55 | self.model.age = 25 56 | self.assertTrue(self.model.validate()) 57 | self.model.age = '25' 58 | self.assertFalse(self.model.validate()) 59 | self.assertEqual(len(self.model.get_errors()), 1) 60 | 61 | def test_model_context(self): 62 | self.model.set_context(None) 63 | self.assertIn('location', self.model.attributes) 64 | 65 | self.model.set_context('undefined_scenario') 66 | self.assertEqual(self.model.attributes, self.model.get( 67 | 'name', 'age', 'gender', 'location')) 68 | 69 | self.model.set_context('personal') 70 | self.assertNotEqual(self.model.attributes, self.model.get( 71 | 'name', 'age', 'gender', 'location')) 72 | -------------------------------------------------------------------------------- /tests/core/test_object.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.0 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | import unittest 12 | from unittest import mock 13 | from rebase.core import Object 14 | 15 | 16 | class TestObject(unittest.TestCase): 17 | def setUp(self): 18 | self.obj = Object( 19 | name='Paul', 20 | age='35', 21 | gender="Male", 22 | location=dict( 23 | city='Paris', 24 | country='France' 25 | ), 26 | is_admin=False, 27 | user='user', 28 | status='inactive', 29 | mother={'name': 'Lucie', 'age':46} 30 | ) 31 | 32 | 33 | def test_object_basic(self): 34 | self.assertIn('name', self.obj.attributes) 35 | self.assertIn('age', self.obj.attributes) 36 | self.assertIn('gender', self.obj.attributes) 37 | 38 | self.assertEqual(self.obj.name, 'Paul') 39 | self.assertEqual(self.obj.age, '35') 40 | self.assertEqual(self.obj.gender, 'Male') 41 | 42 | self.assertDictEqual(self.obj.attributes, self.obj.get( 43 | 'name', 'age', 'gender', 'location', 'is_admin', 'user', 'status', 'mother')) 44 | 45 | @mock.patch.multiple( 46 | Object, 47 | properties=mock.Mock( 48 | return_value={ 49 | 'firstname': 'name', 50 | 'age': ('age', int), 51 | 'gender': ('gender', lambda x: int(x == 'Male')), 52 | 'city': 'location.city', 53 | 'country': ('location.country', lambda x: x.upper()), 54 | 'occupation': ('occupation', lambda x: x), 55 | 'user': ('user', lambda x: x), 56 | 'admin': 'not admin', 57 | 'status': lambda: 'active', 58 | 'date_joined': (lambda: 'today', str), 59 | 'mother': ('mother', Object) 60 | } 61 | ) 62 | ) 63 | def test_object_init(self): 64 | self.setUp() 65 | 66 | self.assertEqual(self.obj.firstname, 'Paul') 67 | self.assertEqual(self.obj.age, 35) 68 | self.assertEqual(self.obj.gender, 1) 69 | self.assertEqual(self.obj.city, 'Paris') 70 | self.assertEqual(self.obj.country, 'FRANCE') 71 | self.assertEqual(self.obj.occupation, None) 72 | self.assertEqual(self.obj.user, 'user') 73 | self.assertEqual(self.obj.admin, None) 74 | self.assertEqual(self.obj.status, 'active') 75 | self.assertEqual(self.obj.date_joined, 'today') 76 | self.assertTrue(isinstance(self.obj.mother, Object)) 77 | 78 | self.assertRaises(AttributeError, getattr, self.obj, 'qwerty') 79 | self.assertRaises(AttributeError, setattr, self.obj, 'qwerty', 'asd') 80 | self.assertIsNone(setattr(self.obj, 'age', 25)) 81 | self.assertIs(getattr(self.obj, 'age'), 25) 82 | self.assertRaises(AttributeError, setattr, self.obj, 'age', '25') 83 | -------------------------------------------------------------------------------- /tests/core/test_validator.py: -------------------------------------------------------------------------------- 1 | """This file is part of the trivago/rebase library. 2 | 3 | # Copyright (c) 2018 trivago N.V. 4 | # License: Apache 2.0 5 | # Source: https://github.com/trivago/rebase 6 | # Version: 1.2.0 7 | # Python Version: 3.6 8 | # Author: Yuv Joodhisty 9 | """ 10 | 11 | import unittest 12 | from unittest import mock 13 | from rebase.core import Validator 14 | 15 | 16 | @mock.patch.multiple( 17 | Validator, 18 | depends_on=mock.Mock( 19 | return_value={ 20 | mock.Mock( 21 | validate=lambda x: True, 22 | errors=[] 23 | ), 24 | mock.Mock( 25 | validate=lambda x: False, 26 | errors=['Error 2'] 27 | ), 28 | } 29 | ) 30 | ) 31 | class TestValidator(unittest.TestCase): 32 | def test_validator_basic(self): 33 | v = Validator() 34 | 35 | self.assertFalse(v.validate('123')) 36 | self.assertIn('Error 2', v.errors) 37 | --------------------------------------------------------------------------------