Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Always set testing cookies, even on pages which do not use them #505

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion waffle/middleware.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,28 @@
from django.http import HttpRequest, HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.utils.encoding import smart_str

from waffle.utils import get_setting
from waffle import get_waffle_flag_model

WaffleFlag = get_waffle_flag_model()


class WaffleMiddleware(MiddlewareMixin):

def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):
"""Ensure testing cookie are always set, even if Waffle isn't used"""
for flag in WaffleFlag.objects.filter(testing=True):
tc = get_setting("TEST_COOKIE") % flag.name
if tc in request.GET:
on = request.GET[tc] == "1"
if not hasattr(request, "waffle_tests"):
request.waffle_tests = {}
request.waffle_tests[flag.name] = on
return self.process_response(request, self.get_response(request))

def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse:
secure = get_setting('SECURE')
max_age = get_setting('MAX_AGE')
Expand Down
11 changes: 4 additions & 7 deletions waffle/tests/test_waffle.py
Original file line number Diff line number Diff line change
Expand Up @@ -374,19 +374,16 @@ def test_testing_flag_header(self):

def test_set_then_unset_testing_flag(self):
waffle.get_waffle_flag_model().objects.create(name='myflag', testing=True)
response = self.client.get('/flag_in_view?dwft_myflag=1')
self.assertEqual(b'on', response.content)

self.client.get('/foo?dwft_myflag=1')
response = self.client.get('/flag_in_view')
self.assertEqual(b'on', response.content)

response = self.client.get('/flag_in_view?dwft_myflag=0')
self.assertEqual(b'off', response.content)

self.client.get('/foo?dwft_myflag=0')
response = self.client.get('/flag_in_view')
self.assertEqual(b'off', response.content)

response = self.client.get('/flag_in_view?dwft_myflag=1')
self.client.get('/foo?dwft_myflag=1')
response = self.client.get('/flag_in_view')
self.assertEqual(b'on', response.content)

@override_settings(DATABASE_ROUTERS=['waffle.tests.base.ReplicationRouter'])
Expand Down
Loading