Skip to content

Commit

Permalink
Avoid updating modified_by from None to None (ansible#11838)
Browse files Browse the repository at this point in the history
This should help the case of inventory updates in particular
  where imported hosts are managed by the system
  • Loading branch information
AlanCoding authored Aug 18, 2022
1 parent e87fabe commit 4a8613c
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 4 deletions.
9 changes: 5 additions & 4 deletions awx/main/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,16 +316,17 @@ def save(self, *args, **kwargs):
user = get_current_user()
if user and not user.id:
user = None
if not self.pk and not self.created_by:
if (not self.pk) and (user is not None) and (not self.created_by):
self.created_by = user
if 'created_by' not in update_fields:
update_fields.append('created_by')
# Update modified_by if any editable fields have changed
new_values = self._get_fields_snapshot()
if (not self.pk and not self.modified_by) or self._values_have_edits(new_values):
self.modified_by = user
if 'modified_by' not in update_fields:
update_fields.append('modified_by')
if self.modified_by != user:
self.modified_by = user
if 'modified_by' not in update_fields:
update_fields.append('modified_by')
super(PrimordialModel, self).save(*args, **kwargs)
self._prior_values_store = new_values

Expand Down
40 changes: 40 additions & 0 deletions awx/main/tests/functional/models/test_base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from unittest import mock
import pytest

from crum import impersonate

from awx.main.models import Host


@pytest.mark.django_db
def test_modified_by_not_changed(inventory):
with impersonate(None):
host = Host.objects.create(name='foo', inventory=inventory)
assert host.modified_by == None
host.variables = {'foo': 'bar'}
with mock.patch('django.db.models.Model.save') as save_mock:
host.save(update_fields=['variables'])
save_mock.assert_called_once_with(update_fields=['variables'])


@pytest.mark.django_db
def test_modified_by_changed(inventory, alice):
with impersonate(None):
host = Host.objects.create(name='foo', inventory=inventory)
assert host.modified_by == None
with impersonate(alice):
host.variables = {'foo': 'bar'}
with mock.patch('django.db.models.Model.save') as save_mock:
host.save(update_fields=['variables'])
save_mock.assert_called_once_with(update_fields=['variables', 'modified_by'])
assert host.modified_by == alice


@pytest.mark.django_db
def test_created_by(inventory, alice):
with impersonate(alice):
host = Host.objects.create(name='foo', inventory=inventory)
assert host.created_by == alice
with impersonate(None):
host = Host.objects.create(name='bar', inventory=inventory)
assert host.created_by == None

0 comments on commit 4a8613c

Please sign in to comment.