from io import StringIO import pytest from django.core.management import call_command from dpdapi.models import Alias, Domain def run(*args): out = StringIO() call_command("import_valiases", *args, stdout=out) return out.getvalue() @pytest.mark.django_db def test_missing_argument(): assert run() == "Missing argument\n" @pytest.mark.django_db def test_missing_file(tmp_path): path = tmp_path / "nope" assert run(str(path)) == f"{path} does not exist\n" @pytest.mark.django_db def test_no_aliases(tmp_path): path = tmp_path / "valiases" path.write_text('*: catchall@example.com\nlist: "|/usr/lib/mailman/mail/mailman post list"\n') assert run(str(path)) == "No aliases found\n" assert not Domain.objects.exists() @pytest.mark.django_db def test_import(tmp_path): path = tmp_path / "valiases" path.write_text( "*: catchall@example.com\n" "ops@example.com: a@example.com,b@example.com\n" 'list@example.com: "|/usr/lib/mailman/mail/mailman post list",list-admin@example.com,c@example.com\n' "ops@example.com: a@example.com\n" ) out = run(str(path)) assert out == ( "Created domain example.com.\n" "Could not import 'ops@example.com=a@example.com', already exists.\n" "Imported 3, skipped 1 existing, total 4\n" ) assert sorted(Alias.objects.values_list("source", "destination")) == [ ("list@example.com", "c@example.com"), ("ops@example.com", "a@example.com"), ("ops@example.com", "b@example.com"), ] @pytest.mark.django_db def test_import_into_existing_domain(tmp_path): Domain.objects.create(name="example.com") path = tmp_path / "valiases" path.write_text("ops@example.com: a@example.com\n") assert run(str(path)) == "Imported 1, skipped 0 existing, total 1\n"