Skip to content

Commit

Permalink
Make CREATE_MISSING_FLAGS logic universal (jazzband#400) (jazzband#427)
Browse files Browse the repository at this point in the history
Before CREATE_MISSING_FLAGS was only respected when `is_active(request)` method was used, now any check against a flag (calling `get(name)`) will trigger the automatic creation of the `Flag` model.
  • Loading branch information
honzakral committed Mar 28, 2022
1 parent 4bb357d commit 9331bc4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 10 deletions.
17 changes: 7 additions & 10 deletions waffle/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,13 @@ def get_from_db(cls, name):
objects = cls.objects
if get_setting('READ_FROM_WRITE_DB'):
objects = objects.using(router.db_for_write(cls))

if get_setting('CREATE_MISSING_FLAGS'):
flag, _created = objects.get_or_create(
name=name, defaults={'everyone': get_setting('FLAG_DEFAULT')}
)
return flag

return objects.get(name=name)

@classmethod
Expand Down Expand Up @@ -247,16 +254,6 @@ def is_active(self, request):
log_level = get_setting('LOG_MISSING_FLAGS')
if log_level:
logger.log(log_level, 'Flag %s not found', self.name)
if get_setting('CREATE_MISSING_FLAGS'):
flag, _created = get_waffle_flag_model().objects.get_or_create(
name=self.name,
defaults={
'everyone': get_setting('FLAG_DEFAULT')
}
)
cache = get_cache()
cache.set(self._cache_key(self.name), flag)

return get_setting('FLAG_DEFAULT')

if get_setting('OVERRIDE'):
Expand Down
10 changes: 10 additions & 0 deletions waffle/tests/test_waffle.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,16 @@ def test_flag_created_dynamically_default_false(self):
def test_flag_created_dynamically_default_true(self):
self.assert_flag_dynamically_created_with_value(True)

@override_settings(WAFFLE_CREATE_MISSING_FLAGS=True)
@override_settings(WAFFLE_FLAG_DEFAULT=True)
def test_flag_created_dynamically_upon_retrieval(self):
FLAG_NAME = 'myflag'
flag_model = waffle.get_waffle_flag_model()
flag = flag_model.get(FLAG_NAME)

assert flag.is_active(get())
assert flag_model.objects.filter(name=FLAG_NAME).exists()

@mock.patch('waffle.models.logger')
def test_no_logging_missing_flag_by_default(self, mock_logger):
request = get()
Expand Down

0 comments on commit 9331bc4

Please sign in to comment.