Skip to content

Commit

Permalink
Merge pull request #122 from dimaqq/docs/testing
Browse files Browse the repository at this point in the history
docs: document how flags can be toggled in tests
  • Loading branch information
willbarton committed Mar 19, 2024
2 parents 9cfbb6c + d98572f commit 5972084
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
36 changes: 36 additions & 0 deletions docs/testing.md
@@ -0,0 +1,36 @@
# Testing

## Testing code that depends on flags

Because `FLAGS` are definable in Django settings, you can use Django's standard `override_settings` to test with a flag off and on.

```python
from django.test import TestCase, override_settings

class FlaggedCodeTestCase(TestCase):
@override_settings(FLAGS={"MY_FLAG": [("boolean", True)]})
def test_flag_enabled(self):
# Do the thing that requires the flag to be enabled

@override_settings(FLAGS={"MY_FLAG": [("boolean", False)]})
def test_flag_disabled(self):
# Do the thing that requires the flag to be disabled
```

Alternatively, you can create a `FlagState` object along the same lines with a boolean condition that is `True` to test the flag-enabled code path, and then create one with a boolean condition that is` False` to test the not-enabled path.


```python
class FlaggedCodeTestCase(TestCase):
def test_flag_enabled(self):
FlagState.objects.create(
name="MY_FLAG", condition="boolean", value="True"
)
# Do the thing that requires the flag to be enabled

def test_flag_disabled(self):
FlagState.objects.create(
name="MY_FLAG", condition="boolean", value="True"
)
# Do the thing that requires the flag to be disabled
```
18 changes: 18 additions & 0 deletions docs/usage.md
Expand Up @@ -65,4 +65,22 @@ urlpatterns = [
]
```

## Testing with flags

A test case that covers both values of the flag may look like this:

```python
from django.test import TestCase, override_settings

class FlaggedCodeTestCase(TestCase):
@override_settings(FLAGS={"MY_FLAG": [("boolean", True)]})
def test_flag_enabled(self):
# Do the thing that requires the flag to be enabled

@override_settings(FLAGS={"MY_FLAG": [("boolean", False)]})
def test_flag_disabled(self):
# Do the thing that requires the flag to be disabled
```


See the [API reference](/api/state) for more details and examples.
1 change: 1 addition & 0 deletions mkdocs.yml
Expand Up @@ -5,6 +5,7 @@ nav:
- Getting started: index.md
- Usage guide: usage.md
- Debugging: debugging.md
- Testing: testing.md
- Settings: settings.md
- Conditions: conditions.md
- Management commands: management_commands.md
Expand Down

0 comments on commit 5972084

Please sign in to comment.