import pytest
from name.models import validate_merged_with, Name
from django.core.exceptions import ValidationError


@pytest.fixture
def merge_candidates(db):
    """Fixture setup to for testing merged validators."""
    primary = Name.objects.create(name='Primary', name_type=0)
    secondary = Name.objects.create(name='Secondary', name_type=0)
    return (primary, secondary)


@pytest.mark.django_db
def test_validate_merged_with_passes(merge_candidates):
    primary, secondary = merge_candidates
    # We will not assert here because failure will raise
    # an exception and cause a failure. Passing validation
    # returns nothing and the test passes.
    validate_merged_with(primary.id)


@pytest.mark.django_db
def test_validate_merged_with_fails(merge_candidates):
    """Tests validate_merged_with_fails.

    This should fail when attempting to circularly merge Names.
    Example: Name1 -> Name2, Name2 -> Name1.
    """
    primary, secondary = merge_candidates

    secondary.merged_with = primary
    primary.merged_with = secondary

    secondary.save()
    primary.save()

    with pytest.raises(ValidationError):
        validate_merged_with(primary.id)

import pytest
from name.models import validate_merged_with, Name
from django.core.exceptions import ValidationError


@pytest.mark.django_db
def test_validate_merged_with_fails_with_unknown_id():
    with pytest.raises(ValidationError):
        validate_merged_with(1)

@pytest.mark.django_db
def test_validate_merged_with_passes():
    primary = Name.objects.create(name='Primary', name_type=0)
    secondary = Name.objects.create(name='Secondary', name_type=0)

    secondary.merged_with = primary
    secondary.save()

    validate_merged_with(secondary.id)


@pytest.mark.django_db
def test_validate_merged_with_fails():
    """Checks that validate_merged_with fails.

    This should fail when attempting to circularly merge Names.
    Example: Name1 -> Name2, Name2 -> Name1.
    """
    primary = Name.objects.create(name='Primary', name_type=0)
    secondary = Name.objects.create(name='Secondary', name_type=0)

    secondary.merged_with = primary
    primary.merged_with = secondary

    secondary.save()
    primary.save()

    with pytest.raises(ValidationError):
        validate_merged_with(primary.id)


@pytest.mark.django_db
def test_validate_merged_with_fails_with_more_than_two_names():
    """Checks that a merge loop constisting of more than two name
    also fails validation.
    """
    primary = Name.objects.create(name='Primary', name_type=0)
    second = Name.objects.create(name='Second', name_type=0)
    third = Name.objects.create(name='Third', name_type=0)

    second.merged_with = primary
    second.save()

    third.merged_with = second
    third.save()

    primary.merged_with = third
    primary.save()

    with pytest.raises(ValidationError):
        validate_merged_with(primary.id)

Update the validate_merge_with tests.