Skip to content

Commit 8e2bcb3

Browse files
authored
Merge pull request #90 from networktocode/dga-fix-86
Convert actions to Enum
2 parents e3501ee + 443d833 commit 8e2bcb3

File tree

4 files changed

+34
-24
lines changed

4 files changed

+34
-24
lines changed

diffsync/diff.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
from .exceptions import ObjectAlreadyExists
2222
from .utils import intersection, OrderedDefaultDict
23+
from .enum import DiffSyncActions
2324

2425

2526
class Diff:
@@ -105,9 +106,9 @@ def order_children_default(cls, children: Mapping) -> Iterator["DiffElement"]:
105106
def summary(self) -> Mapping[Text, int]:
106107
"""Build a dict summary of this Diff and its child DiffElements."""
107108
summary = {
108-
"create": 0,
109-
"update": 0,
110-
"delete": 0,
109+
DiffSyncActions.CREATE.value: 0,
110+
DiffSyncActions.UPDATE.value: 0,
111+
DiffSyncActions.DELETE.value: 0,
111112
"no-change": 0,
112113
}
113114
for child in self.get_children():
@@ -220,22 +221,22 @@ def __len__(self):
220221
return total
221222

222223
@property
223-
def action(self) -> Optional[Text]:
224+
def action(self) -> Optional[DiffSyncActions]:
224225
"""Action, if any, that should be taken to remediate the diffs described by this element.
225226
226227
Returns:
227-
str: "create", "update", "delete", or None
228+
DiffSyncActions ("create", "update", "delete", or None)
228229
"""
229230
if self.source_attrs is not None and self.dest_attrs is None:
230-
return "create"
231+
return DiffSyncActions.CREATE
231232
if self.source_attrs is None and self.dest_attrs is not None:
232-
return "delete"
233+
return DiffSyncActions.DELETE
233234
if (
234235
self.source_attrs is not None
235236
and self.dest_attrs is not None
236237
and any(self.source_attrs[attr_key] != self.dest_attrs[attr_key] for attr_key in self.get_attrs_keys())
237238
):
238-
return "update"
239+
return DiffSyncActions.UPDATE
239240

240241
return None
241242

@@ -328,13 +329,13 @@ def has_diffs(self, include_children: bool = True) -> bool:
328329
def summary(self) -> Mapping[Text, int]:
329330
"""Build a summary of this DiffElement and its children."""
330331
summary = {
331-
"create": 0,
332-
"update": 0,
333-
"delete": 0,
332+
DiffSyncActions.CREATE.value: 0,
333+
DiffSyncActions.UPDATE.value: 0,
334+
DiffSyncActions.DELETE.value: 0,
334335
"no-change": 0,
335336
}
336337
if self.action:
337-
summary[self.action] += 1
338+
summary[self.action.value] += 1
338339
else:
339340
summary["no-change"] += 1
340341
child_summary = self.child_diff.summary()

diffsync/enum.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,12 @@ class DiffSyncStatus(enum.Enum):
7373
SUCCESS = "success"
7474
FAILURE = "failure"
7575
ERROR = "error"
76+
77+
78+
class DiffSyncActions(enum.Enum):
79+
"""List of valid Action for DiffSyncModel."""
80+
81+
CREATE = "create"
82+
UPDATE = "update"
83+
DELETE = "delete"
84+
NO_CHANGE = None

diffsync/helpers.py

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import structlog # type: ignore
2121

2222
from .diff import Diff, DiffElement
23-
from .enum import DiffSyncModelFlags, DiffSyncFlags, DiffSyncStatus
23+
from .enum import DiffSyncModelFlags, DiffSyncFlags, DiffSyncStatus, DiffSyncActions
2424
from .exceptions import ObjectNotFound, ObjectNotCreated, ObjectNotUpdated, ObjectNotDeleted, ObjectCrudException
2525
from .utils import intersection, symmetric_difference
2626

@@ -296,7 +296,7 @@ def __init__( # pylint: disable=too-many-arguments
296296
# Local state maintained during synchronization
297297
self.logger: structlog.BoundLogger = self.base_logger
298298
self.model_class: Type["DiffSyncModel"]
299-
self.action: Optional[str] = None
299+
self.action: Optional[DiffSyncActions] = None
300300

301301
def incr_elements_processed(self, delta: int = 1):
302302
"""Increment self.elements_processed, then call self.callback if present."""
@@ -353,11 +353,11 @@ def sync_diff_element(self, element: DiffElement, parent_model: "DiffSyncModel"
353353
self.logger.warning("No object resulted from sync, will not process child objects.")
354354
return changed
355355

356-
if self.action == "create":
356+
if self.action == DiffSyncActions.CREATE:
357357
if parent_model:
358358
parent_model.add_child(model)
359359
self.dst_diffsync.add(model)
360-
elif self.action == "delete":
360+
elif self.action == DiffSyncActions.DELETE:
361361
if parent_model:
362362
parent_model.remove_child(model)
363363
if model.model_flags & DiffSyncModelFlags.SKIP_CHILDREN_ON_DELETE:
@@ -390,16 +390,16 @@ def sync_model(
390390
return (False, model)
391391

392392
try:
393-
self.logger.debug(f"Attempting model {self.action}")
394-
if self.action == "create":
393+
self.logger.debug(f"Attempting model {self.action.value}")
394+
if self.action == DiffSyncActions.CREATE:
395395
if model is not None:
396396
raise ObjectNotCreated(f"Failed to create {self.model_class.get_type()} {ids} - it already exists!")
397397
model = self.model_class.create(diffsync=self.dst_diffsync, ids=ids, attrs=attrs)
398-
elif self.action == "update":
398+
elif self.action == DiffSyncActions.UPDATE:
399399
if model is None:
400400
raise ObjectNotUpdated(f"Failed to update {self.model_class.get_type()} {ids} - not found!")
401401
model = model.update(attrs=attrs)
402-
elif self.action == "delete":
402+
elif self.action == DiffSyncActions.DELETE:
403403
if model is None:
404404
raise ObjectNotDeleted(f"Failed to delete {self.model_class.get_type()} {ids} - not found!")
405405
model = model.delete()
@@ -410,7 +410,7 @@ def sync_model(
410410
status, message = model.get_status()
411411
else:
412412
status = DiffSyncStatus.FAILURE
413-
message = f"{self.model_class.get_type()} {self.action} did not return the model object."
413+
message = f"{self.model_class.get_type()} {self.action.value} did not return the model object."
414414

415415
except ObjectCrudException as exception:
416416
status = DiffSyncStatus.ERROR
@@ -424,7 +424,7 @@ def sync_model(
424424

425425
return (True, model)
426426

427-
def log_sync_status(self, action: Optional[str], status: DiffSyncStatus, message: str):
427+
def log_sync_status(self, action: Optional[DiffSyncActions], status: DiffSyncStatus, message: str):
428428
"""Log the current sync status at the appropriate verbosity with appropriate context.
429429
430430
Helper method to `sync_diff_element`/`sync_model`.

tests/unit/test_diffsync.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -619,7 +619,7 @@ def check_sync_logs_against_diff(diffsync, diff, log, errors_permitted=False):
619619

620620
assert {
621621
("action", element.action),
622-
("event", f"Attempting model {element.action}"),
622+
("event", f"Attempting model {element.action.value}"),
623623
("level", "debug"),
624624
} <= begin_event.items()
625625
# attrs_diffs dict is unhashable so we can't include it in the above set comparison
@@ -632,7 +632,7 @@ def check_sync_logs_against_diff(diffsync, diff, log, errors_permitted=False):
632632
if complete_event["status"] == "success":
633633
assert {
634634
("action", element.action),
635-
("event", f"{element.action.title()}d successfully"),
635+
("event", f"{element.action.value.title()}d successfully"),
636636
("level", "info"),
637637
("status", "success"),
638638
} <= complete_event.items()

0 commit comments

Comments
 (0)