from unittest.mock import Mock

import pytest
from rest_framework.test import APIRequestFactory

from core.backends.filters import SearchAllFieldsBackend
from devices.models.device import Device

request = Mock()


@pytest.mark.django_db
@pytest.mark.unit
class TestSearchAllFieldsBackend:
    """Test DRF Filter backend."""
    count = 10

    @pytest.fixture(autouse=True)
    def setup_test(self):
        for i in range(self.count):
            if i % 2:
                description = f'test description_{i}'
            else:
                description = f'test text'
            Device(name=f'title_{i}', description=description, ip=f'2.2.2.{i}',
                   port=f'9{i}99', type='firewall').save()

    @pytest.mark.parametrize('search_string, count', (
            ('test', 10),
            ('1', 1),
            ('description', 5),
            ('text', 5),
            ('mama', 0),
            ('', 10)
    ))
    def test_query_count(self, search_string, count):
        """Test count after filter."""
        filter = SearchAllFieldsBackend()
        request.query_params = {'search': search_string}

        before_queryset = Device.objects.all()
        assert len(before_queryset) == self.count
        queryset_after = filter.filter_queryset(request=request, queryset=before_queryset, view=None)
        assert len(queryset_after) == count
