Repository: proteanhq/protean

Issue:
Allow `Entity` to accept keyword arguments for `update`
Entity accepts attributes to be updated as a dictionary. So the invocation would be something like `entry.update({'votes': entry.votes+1})`.

The proposal is to enhance `update` method to accept keyword arguments too, so that we could do this: `entry.update(votes=entry.votes+1)`

Discussion:
codecov-io: # [Codecov](https://codecov.io/gh/proteanhq/protean/pull/62?src=pr&el=h1) Report
> Merging [#62](https://codecov.io/gh/proteanhq/protean/pull/62?src=pr&el=desc) into [master](https://codecov.io/gh/proteanhq/protean/commit/7bed76610fc19318a364eb90f2aab22e51990878?src=pr&el=desc) will **decrease** coverage by `0.11%`.
> The diff coverage is `76.92%`.

[![Impacted file tree graph](https://codecov.io/gh/proteanhq/protean/pull/62/graphs/tree.svg?width=650&token=0sFuFdLBOx&height=150&src=pr)](https://codecov.io/gh/proteanhq/protean/pull/62?src=pr&el=tree)

```diff
@@            Coverage Diff             @@
##           master      #62      +/-   ##
==========================================
- Coverage   79.97%   79.85%   -0.12%     
==========================================
  Files          36       36              
  Lines        1418     1425       +7     
  Branches      230      234       +4     
==========================================
+ Hits         1134     1138       +4     
- Misses        185      186       +1     
- Partials       99      101       +2
```


| [Impacted Files](https://codecov.io/gh/proteanhq/protean/pull/62?src=pr&el=tree) | Coverage Δ | |
|---|---|---|
| [src/protean/core/usecase/generic.py](https://codecov.io/gh/proteanhq/protean/pull/62/diff?src=pr&el=tree#diff-c3JjL3Byb3RlYW4vY29yZS91c2VjYXNlL2dlbmVyaWMucHk=) | `91.66% <100%> (ø)` | :arrow_up: |
| [src/protean/core/entity.py](https://codecov.io/gh/proteanhq/protean/pull/62/diff?src=pr&el=tree#diff-c3JjL3Byb3RlYW4vY29yZS9lbnRpdHkucHk=) | `92.35% <75%> (-1.65%)` | :arrow_down: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/proteanhq/protean/pull/62?src=pr&el=continue).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/proteanhq/protean/pull/62?src=pr&el=footer). Last update [7bed766...6f0248d](https://codecov.io/gh/proteanhq/protean/pull/62?src=pr&el=lastupdated). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments).


Patch:
diff --git a/docs/index.rst b/docs/index.rst
index 875967a5..02758a8e 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -45,6 +45,10 @@ The User Guide
 
 This part of the documentation introduces some background information about protean, then focuses on step-by-step instructions for getting the most out of Protean.
 
+.. note:: Protean's test code is littered with usage of a certain `Dog` class. If you find that discomforting, replace `Dog` with `CuteLittlePuppyDog` everywhere.
+
+    **Disclosure**: No real dog was harmed in the process of building this framework.
+
 .. toctree::
    :maxdepth: 2
    :caption: User Guide
diff --git a/src/protean/core/entity.py b/src/protean/core/entity.py
index 2dc45044..46e08f9d 100644
--- a/src/protean/core/entity.py
+++ b/src/protean/core/entity.py
@@ -122,9 +122,9 @@ class Entity(metaclass=EntityBase):
     def __init__(self, *template, **kwargs):
         """
         Initialise the entity object.
-        
+
         During initialization, set value on fields if vaidation passes.
-        
+
         This initialization technique supports keyword arguments as well as dictionaries. You
             can even use a template for initial data.
         """
@@ -174,16 +174,31 @@ class Entity(metaclass=EntityBase):
         except ValidationError as err:
             self.errors[field_name] = err.messages
 
-    def update_data(self, data):
+    def _update_data(self, *data_dict, **kwargs):
         """
-        Update the entity with the given set of values
+        A private method to process and update entity values correctly.
 
-        :param data: the dictionary of values to be updated for the entity
+        :param data: A dictionary of values to be updated for the entity
+        :param kwargs: keyword arguments with key-value pairs to be updated
         """
 
         # Load each of the fields given in the data dictionary
         self.errors = {}
-        for field_name, val in data.items():
+
+        for data in data_dict:
+            if not isinstance(data, dict):
+                raise AssertionError(
+                    f'Positional argument "{data}" passed must be a dict.'
+                    f'This argument serves as a template for loading common '
+                    f'values.'
+                )
+            for field_name, val in data.items():
+                field_obj = self.meta_.declared_fields.get(field_name, None)
+                if field_obj:
+                    self._setattr(field_name, field_obj, val)
+
+        # Now load against the keyword arguments
+        for field_name, val in kwargs.items():
             field_obj = self.meta_.declared_fields.get(field_name, None)
             if field_obj:
                 self._setattr(field_name, field_obj, val)
@@ -319,22 +334,27 @@ class Entity(metaclass=EntityBase):
 
         return entity
 
-    def update(self, data: dict) -> 'Entity':
+    def update(self, *data, **kwargs) -> 'Entity':
         """Update a Record in the repository.
 
         Also performs unique validations before creating the entity.
 
-        :param data: A dictionary of record properties to be updated
+        Supports both dictionary and keyword argument updates to the entity::
+
+            dog.update({'age': 10})
+
+            dog.update(age=10)
+
+        :param data: Dictionary of values to be updated for the entity
+        :param kwargs: keyword arguments with key-value pairs to be updated
         """
-        logger.debug(
-            f'Updating existing `{self.__class__.__name__}` object with id '
-            f'{self.id} using data {data}')
+        logger.debug(f'Updating existing `{self.__class__.__name__}` object with id {self.id}')
 
         # Fetch Model class and connected-adapter from Repository Factory
         model_cls, adapter = self.__class__._retrieve_model()
 
         # Update entity's data attributes
-        self.update_data(data)
+        self._update_data(*data, **kwargs)
 
         # Do unique checks, update the record and return the Entity
         self._validate_unique(create=False)
diff --git a/src/protean/core/usecase/generic.py b/src/protean/core/usecase/generic.py
index e0ab6c2c..7685eadc 100644
--- a/src/protean/core/usecase/generic.py
+++ b/src/protean/core/usecase/generic.py
@@ -176,7 +176,7 @@ class UpdateUseCase(UseCase):
         entity = request_object.entity_cls.get(request_object.identifier)
 
         # Update the object and return the updated data
-        resource = entity.update(data=request_object.data)
+        resource = entity.update(request_object.data)
         return ResponseSuccess(Status.SUCCESS, resource)
 
 


Test patch:
diff --git a/tests/core/test_entity.py b/tests/core/test_entity.py
index d17b6b4c..f12f9be8 100644
--- a/tests/core/test_entity.py
+++ b/tests/core/test_entity.py
@@ -137,23 +137,42 @@ class TestEntity:
         dog = Dog.create(id=11344234, name='Johnny', owner='John')
         dog.delete()
         with pytest.raises(ObjectNotFoundError):
-            dog.update(data=dict(age=10))
+            dog.update({'age': 10})
 
-    def test_update(self):
+    def test_update_with_dict(self):
         """ Update an existing entity in the repository"""
         dog = Dog.create(id=2, name='Johnny', owner='Carey', age=2)
 
-        dog.update(data=dict(age=10))
+        dog.update({'age':10})
         u_dog = Dog.get(2)
         assert u_dog is not None
         assert u_dog.age == 10
 
+    def test_update_with_kwargs(self):
+        """ Update an existing entity in the repository"""
+        dog = Dog.create(id=2, name='Johnny', owner='Carey', age=2)
+
+        dog.update(age=10)
+        u_dog = Dog.get(2)
+        assert u_dog is not None
+        assert u_dog.age == 10
+
+    def test_update_with_dict_and_kwargs(self):
+        """ Update an existing entity in the repository"""
+        dog = Dog.create(id=2, name='Johnny', owner='Carey', age=2)
+
+        dog.update({'owner': 'Stephen'}, age=10)
+        u_dog = Dog.get(2)
+        assert u_dog is not None
+        assert u_dog.age == 10
+        assert u_dog.owner == 'Stephen'
+
     def test_that_update_runs_validations(self):
         """Try updating with invalid values"""
         dog = Dog.create(id=1, name='Johnny', owner='Carey', age=2)
 
         with pytest.raises(ValidationError):
-            dog.update(data=dict(age='x'))
+            dog.update(age='x')
 
     def test_unique(self):
         """ Test the unique constraints for the entity """
diff --git a/tests/core/test_repository.py b/tests/core/test_repository.py
index cb68df20..3383eecf 100644
--- a/tests/core/test_repository.py
+++ b/tests/core/test_repository.py
@@ -40,7 +40,7 @@ class TestRepository:
         """ Update an existing entity in the repository"""
         dog = Dog.create(id=2, name='Johnny', owner='Carey', age=2)
 
-        dog.update(data=dict(age=10))
+        dog.update(age=10)
         u_dog = Dog.get(2)
         assert u_dog is not None
         assert u_dog.age == 10
@@ -50,7 +50,7 @@ class TestRepository:
         dog = Dog.create(id=1, name='Johnny', owner='Carey', age=2)
 
         with pytest.raises(ValidationError):
-            dog.update(data=dict(age='x'))
+            dog.update(age='x')
 
     def test_unique(self):
         """ Test the unique constraints for the entity """