from io import StringIO import pytest from django.contrib.auth.models import User from django.core.management import call_command from django.core.management.base import CommandError @pytest.fixture def superuser_env(monkeypatch): monkeypatch.setenv("DJANGO_SUPERUSER_USERNAME", "admin") monkeypatch.setenv("DJANGO_SUPERUSER_EMAIL", "admin@example.com") monkeypatch.setenv("DJANGO_SUPERUSER_PASSWORD", "secret") @pytest.mark.django_db def test_creates_superuser_when_missing(superuser_env): output = StringIO() call_command("ensure_superuser", stdout=output) user = User.objects.get(username="admin") assert user.is_superuser assert user.check_password("secret") assert "Создан суперпользователь admin" in output.getvalue() @pytest.mark.django_db def test_skips_when_superuser_exists(superuser_env): User.objects.create_superuser("other", "other@example.com", "other-secret") output = StringIO() call_command("ensure_superuser", stdout=output) assert User.objects.filter(is_superuser=True).count() == 1 assert not User.objects.filter(username="admin").exists() assert "уже есть" in output.getvalue() @pytest.mark.django_db def test_skips_without_password(monkeypatch): monkeypatch.delenv("DJANGO_SUPERUSER_PASSWORD", raising=False) output = StringIO() call_command("ensure_superuser", stdout=output) assert not User.objects.exists() assert "DJANGO_SUPERUSER_PASSWORD" in output.getvalue() @pytest.mark.django_db def test_errors_if_username_taken_by_regular_user(superuser_env): User.objects.create_user("admin", "admin@example.com", "user-secret") with pytest.raises(CommandError, match="не суперпользователь"): call_command("ensure_superuser")