|
| 1 | +from typing import Any, Tuple |
| 2 | + |
| 3 | +import pytest |
| 4 | +from django_test_migrations.migrator import Migrator |
| 5 | + |
| 6 | + |
| 7 | +@pytest.mark.django_db |
| 8 | +def test_migrations_0001_initial(migrator: Migrator) -> None: |
| 9 | + old_state = migrator.apply_initial_migration(("rest_framework_api_key", None)) |
| 10 | + |
| 11 | + with pytest.raises(LookupError): |
| 12 | + old_state.apps.get_model("rest_framework_api_key", "APIKey") |
| 13 | + |
| 14 | + new_state = migrator.apply_tested_migration( |
| 15 | + ("rest_framework_api_key", "0001_initial") |
| 16 | + ) |
| 17 | + APIKey = new_state.apps.get_model("rest_framework_api_key", "APIKey") |
| 18 | + assert APIKey.objects.count() == 0 |
| 19 | + |
| 20 | + |
| 21 | +@pytest.mark.django_db |
| 22 | +def test_migrations_0004_prefix_hashed_key(migrator: Migrator) -> None: |
| 23 | + from django.contrib.auth.hashers import make_password |
| 24 | + from django.utils.crypto import get_random_string |
| 25 | + |
| 26 | + def _generate() -> Tuple[str, str]: |
| 27 | + # Replicate bejavior before PR #62 (i.e. before v1.4). |
| 28 | + prefix = get_random_string(8) |
| 29 | + secret_key = get_random_string(32) |
| 30 | + key = prefix + "." + secret_key |
| 31 | + key_id = prefix + "." + make_password(key) |
| 32 | + return key, key_id |
| 33 | + |
| 34 | + def _assign_key(obj: Any) -> None: |
| 35 | + # Replicate bejavior before PR #62 (i.e. before v1.4). |
| 36 | + _, hashed_key = _generate() |
| 37 | + pk = hashed_key |
| 38 | + prefix, _, hashed_key = hashed_key.partition(".") |
| 39 | + |
| 40 | + obj.id = pk |
| 41 | + obj.prefix = prefix |
| 42 | + obj.hashed_key = hashed_key |
| 43 | + |
| 44 | + old_state = migrator.apply_initial_migration( |
| 45 | + ("rest_framework_api_key", "0003_auto_20190623_1952") |
| 46 | + ) |
| 47 | + |
| 48 | + APIKey = old_state.apps.get_model("rest_framework_api_key", "APIKey") |
| 49 | + |
| 50 | + # Create a key as it if were created before PR #62 (i.e. before v1.4). |
| 51 | + api_key = APIKey.objects.create(name="test") |
| 52 | + _assign_key(api_key) |
| 53 | + api_key.save() |
| 54 | + prefix, _, hashed_key = api_key.id.partition(".") |
| 55 | + |
| 56 | + # Apply migration added by PR #62. |
| 57 | + new_state = migrator.apply_tested_migration( |
| 58 | + ("rest_framework_api_key", "0004_prefix_hashed_key") |
| 59 | + ) |
| 60 | + APIKey = new_state.apps.get_model("rest_framework_api_key", "APIKey") |
| 61 | + |
| 62 | + # Ensure new `prefix`` and `hashed_key` fields were successfully populated. |
| 63 | + api_key = APIKey.objects.get(id=api_key.id) |
| 64 | + assert api_key.prefix == prefix |
| 65 | + assert api_key.hashed_key == hashed_key |
0 commit comments