# Django Assertions

All Django TestCase assertion methods for comprehensive testing capabilities. These assertions provide Django-specific testing functionality including HTTP response testing, form validation, template usage, and HTML/JSON comparison.

## Capabilities

### HTTP Response Assertions

Test HTTP responses, redirects, and response content.

```python { .api }
def assertRedirects(
    response: HttpResponseBase,
    expected_url: str,
    status_code: int = 302,
    target_status_code: int = 200,
    msg_prefix: str = "",
    fetch_redirect_response: bool = True
) -> None:
    """
    Assert that response is a redirect to expected URL.
    
    Args:
        response: HTTP response object
        expected_url: Expected redirect target URL
        status_code: Expected redirect status code (default: 302)
        target_status_code: Expected final response status (default: 200)
        msg_prefix: Optional message prefix for assertion errors
        fetch_redirect_response: Whether to fetch and check final response
    """

def assertContains(
    response: HttpResponseBase,
    text: object,
    count: Optional[int] = None,
    status_code: int = 200,
    msg_prefix: str = "",
    html: bool = False
) -> None:
    """
    Assert that response contains specified text.
    
    Args:
        response: HTTP response object
        text: Text that should be present in response
        count: Expected number of occurrences (None for any)
        status_code: Expected response status code (default: 200)
        msg_prefix: Optional message prefix for assertion errors
        html: Whether to compare as HTML (ignores whitespace differences)
    """

def assertNotContains(
    response: HttpResponseBase,
    text: object,
    status_code: int = 200,
    msg_prefix: str = "",
    html: bool = False
) -> None:
    """
    Assert that response does not contain specified text.
    
    Args:
        response: HTTP response object
        text: Text that should not be present in response
        status_code: Expected response status code (default: 200)
        msg_prefix: Optional message prefix for assertion errors
        html: Whether to compare as HTML (ignores whitespace differences)
    """

def assertURLEqual(url1: str, url2: str, msg_prefix: str = "") -> None:
    """
    Assert that two URLs are equal, ignoring order of query parameters.
    
    Args:
        url1: First URL to compare
        url2: Second URL to compare
        msg_prefix: Optional message prefix for assertion errors
    """
```

### Template Assertions

Test template usage and rendering.

```python { .api }
def assertTemplateUsed(
    response: Optional[HttpResponseBase] = None,
    template_name: Optional[str] = None,
    msg_prefix: str = "",
    count: Optional[int] = None
):
    """
    Assert that specified template was used in rendering response.
    
    Args:
        response: HTTP response object (or None for last response)
        template_name: Expected template name
        msg_prefix: Optional message prefix for assertion errors
        count: Expected number of times template was used
    """

def assertTemplateNotUsed(
    response: Optional[HttpResponseBase] = None,
    template_name: Optional[str] = None,
    msg_prefix: str = ""
):
    """
    Assert that specified template was not used in rendering response.
    
    Args:
        response: HTTP response object (or None for last response)
        template_name: Template name that should not have been used
        msg_prefix: Optional message prefix for assertion errors
    """
```

### Form Assertions

Test form validation and errors.

```python { .api }
def assertFormError(
    form: forms.BaseForm,
    field: Optional[str],
    errors: Union[str, Sequence[str]],
    msg_prefix: str = ""
) -> None:
    """
    Assert that form has specific validation errors.
    
    Args:
        form: Django form instance
        field: Field name with error (None for non-field errors)
        errors: Expected error message(s)
        msg_prefix: Optional message prefix for assertion errors
    """

def assertFormSetError(
    formset: forms.BaseFormSet,
    form_index: Optional[int],
    field: Optional[str],
    errors: Union[str, Sequence[str]],
    msg_prefix: str = ""
) -> None:
    """
    Assert that formset has specific validation errors.
    
    Args:
        formset: Django formset instance
        form_index: Index of form with error (None for formset errors)
        field: Field name with error (None for non-field errors)
        errors: Expected error message(s)
        msg_prefix: Optional message prefix for assertion errors
    """
```

### HTML/XML Assertions

Test HTML and XML content with intelligent comparison.

```python { .api }
def assertHTMLEqual(html1: str, html2: str, msg: Optional[str] = None) -> None:
    """
    Assert that HTML strings are equivalent, ignoring whitespace.
    
    Args:
        html1: First HTML string
        html2: Second HTML string
        msg: Optional custom assertion message
    """

def assertHTMLNotEqual(html1: str, html2: str, msg: Optional[str] = None) -> None:
    """
    Assert that HTML strings are not equivalent.
    
    Args:
        html1: First HTML string
        html2: Second HTML string
        msg: Optional custom assertion message
    """

def assertInHTML(
    needle: str,
    haystack: str,
    count: Optional[int] = None,
    msg_prefix: str = ""
) -> None:
    """
    Assert that HTML fragment is present in HTML document.
    
    Args:
        needle: HTML fragment to search for
        haystack: HTML document to search in
        count: Expected number of occurrences (None for any)
        msg_prefix: Optional message prefix for assertion errors
    """

def assertXMLEqual(xml1: str, xml2: str, msg: Optional[str] = None) -> None:
    """
    Assert that XML strings are equivalent.
    
    Args:
        xml1: First XML string
        xml2: Second XML string
        msg: Optional custom assertion message
    """

def assertXMLNotEqual(xml1: str, xml2: str, msg: Optional[str] = None) -> None:
    """
    Assert that XML strings are not equivalent.
    
    Args:
        xml1: First XML string
        xml2: Second XML string
        msg: Optional custom assertion message
    """
```

### JSON Assertions

Test JSON content and structure.

```python { .api }
def assertJSONEqual(raw: str, expected_data: Any, msg: Optional[str] = None) -> None:
    """
    Assert that JSON string matches expected data structure.
    
    Args:
        raw: JSON string to parse and compare
        expected_data: Expected Python data structure
        msg: Optional custom assertion message
    """

def assertJSONNotEqual(raw: str, expected_data: Any, msg: Optional[str] = None) -> None:
    """
    Assert that JSON string does not match expected data structure.
    
    Args:
        raw: JSON string to parse and compare
        expected_data: Python data structure that should not match
        msg: Optional custom assertion message
    """
```

### Database Assertions

Test database queries and QuerySet behavior.

```python { .api }
def assertQuerySetEqual(
    qs,
    values,
    transform=repr,
    ordered: bool = True,
    msg: Optional[str] = None
) -> None:
    """
    Assert that QuerySet matches expected values.
    
    Args:
        qs: QuerySet to test
        values: Expected values (list)
        transform: Function to transform QuerySet items for comparison
        ordered: Whether order matters in comparison
        msg: Optional custom assertion message
    """

def assertNumQueries(
    num: int,
    func=None,
    *args,
    using: str = "default",
    **kwargs
):
    """
    Assert that function executes exact number of database queries.
    
    Args:
        num: Expected number of queries
        func: Function to execute (None for context manager usage)
        args: Positional arguments for function
        using: Database alias to monitor
        kwargs: Keyword arguments for function
        
    Returns:
        Context manager if func is None, otherwise function result
    """
```

### Exception and Warning Assertions

Test exception and warning behavior.

```python { .api }
def assertRaisesMessage(
    expected_exception: type[Exception],
    expected_message: str,
    *args,
    **kwargs
):
    """
    Assert that exception is raised with specific message.
    
    Args:
        expected_exception: Expected exception class
        expected_message: Expected exception message
        args: Positional arguments for callable
        kwargs: Keyword arguments for callable
        
    Returns:
        Context manager for use with 'with' statement
    """

def assertWarnsMessage(
    expected_warning: Warning,
    expected_message: str,
    *args,
    **kwargs
):
    """
    Assert that warning is issued with specific message.
    
    Args:
        expected_warning: Expected warning class
        expected_message: Expected warning message
        args: Positional arguments for callable
        kwargs: Keyword arguments for callable
        
    Returns:
        Context manager for use with 'with' statement
    """
```

### Field Testing Assertions

Test form field validation behavior.

```python { .api }
def assertFieldOutput(
    fieldclass,
    valid,
    invalid,
    field_args=None,
    field_kwargs=None,
    empty_value: str = ""
) -> None:
    """
    Assert that form field behaves correctly with valid and invalid inputs.
    
    Args:
        fieldclass: Form field class to test
        valid: Dict of {input: expected_output} for valid inputs
        invalid: List of inputs that should be invalid
        field_args: Positional arguments for field constructor
        field_kwargs: Keyword arguments for field constructor
        empty_value: Expected output for empty input
    """
```

### Message Framework Assertions (Django 5.0+)

Test Django's message framework.

```python { .api }
def assertMessages(
    response: HttpResponseBase,
    expected_messages: Sequence[Message],
    *args,
    ordered: bool = True
) -> None:
    """
    Assert that response contains expected messages.
    
    Available in Django 5.0+. Tests messages added via Django's
    message framework.
    
    Args:
        response: HTTP response object
        expected_messages: Expected message objects
        args: Additional arguments
        ordered: Whether message order matters
    """
```

## Assertion Types

```python { .api }
from django.http import HttpResponseBase, HttpResponse
from django.forms import BaseForm, BaseFormSet
from django.contrib.messages import Message
from typing import Any, Optional, Union, Sequence, Callable, ContextManager

# Response types
HttpResponseType = HttpResponseBase
JsonData = Any  # JSON-serializable data

# Form types  
FormType = BaseForm
FormSetType = BaseFormSet
ValidationErrors = Union[str, Sequence[str]]

# HTML/XML content types
HtmlContent = str
XmlContent = str
JsonContent = str

# QuerySet comparison types
QuerySetValues = Sequence[Any]
TransformFunction = Callable[[Any], Any]

# Exception/Warning types
ExceptionClass = type[Exception]
WarningClass = type[Warning]
ExceptionMessage = str
WarningMessage = str

# Field testing types
FieldClass = type[BaseForm]
ValidInputs = dict[Any, Any]
InvalidInputs = Sequence[Any]
FieldArgs = Sequence[Any]
FieldKwargs = dict[str, Any]
```