Exemplo n.º 1
0
 def setUp(self):
     self.validity_tester_patcher = patch(self.validity_tester)
     self.validity_tester_mock = self.validity_tester_patcher.start()
     function = Mock()
     function.__name__ = str('function')
     self.obj = Mock()
     self.function = function
     self.decorated_function = self.decorator(self.function)
Exemplo n.º 2
0
 def setUp(self):
     self.validity_tester_patcher = patch(self.validity_tester)
     self.validity_tester_mock = self.validity_tester_patcher.start()
     function = Mock()
     function.__name__ = str('function')
     self.obj = Mock()
     self.function = function
     self.decorated_function = self.decorator(self.function)
 def setUp(self):
     self.whitelist_mock = Mock()
     self.whitelist_mock.filter_matching.return_value = MagicMock()
     self.resolver_mock = Mock()
     self.resolver_mock.get_urls_and_locations.return_value = MagicMock()
     self.url_tester_mock = Mock()
     self.tested_instance = GeneralizedURLTester(self.url_tester_mock,
                                                 self.whitelist_mock,
                                                 self.resolver_mock)
def get_response_mock(url):
    """Get a mock representing a response to a request.

    :param url: response URL
    :returns: an instance of mock representing a response
    """
    response = Mock()
    response.url = url
    return response
def get_url_tester_mock(identifier):
    """Get a mock of a URL tester object.

    :param identifier: an identifier for a URL tester object
    to be returned
    :returns: an instance of Mock representing a URL tester object
    """
    source = Mock()
    source.identifier = identifier
    return source
Exemplo n.º 6
0
    def setUp(self):
        self.value_constructor_patcher = patch.object(self.class_to_test,
                                                      'factory', Mock())
        self.value_constructor_mock = self.value_constructor_patcher.start()

        self.name_from_ip_patcher = patch('spam_lists.structures.name_from_ip')
        self.name_from_ip_mock = self.name_from_ip_patcher.start()

        self.tested_instance = self.class_to_test(Mock())
        super(IPAddressTestMixin, self).setUp()
 def setUp(self):
     self.host_factory_mock = Mock()
     self.host_factory_mock.side_effect = host_collection_host_factory
     self.tested_instance = self.constructor(
         'test_host_collection',
         self.classification,
         host_factory=self.host_factory_mock)
Exemplo n.º 8
0
    def hp_hosts_get(url):
        """Get mock representing a response for a GET request.

        :param url: a request address
        :returns: a Mock instance representing response object expected
        by HpHosts
        """
        query_string = urlparse(url).query
        query_data = parse_qs(query_string)
        content = 'Not Listed'
        host = query_data['s'][0]
        if host in listed_hosts:
            content = 'Listed,{}'.format(class_str)
        response = Mock()
        response.text = content
        return response
Exemplo n.º 9
0
    def hp_hosts_get(url):
        """Get mock representing a response for a GET request.

        :param url: a request address
        :returns: a Mock instance representing response object expected
        by HpHosts
        """
        query_string = urlparse(url).query
        query_data = parse_qs(query_string)
        content = 'Not Listed'
        host = query_data['s'][0]
        if host in listed_hosts:
            content = 'Listed,{}'.format(class_str)
        response = Mock()
        response.text = content
        return response
Exemplo n.º 10
0
    def test_lt_for_not_comparable_values(self, _, result):
        self.tested_instance.value.__lt__.side_effect = TypeError

        str_value = self.tested_instance.to_unicode()
        str_value.__lt__.return_value = result
        other = Mock()

        assertion = self.assertTrue if result else self.assertFalse
        assertion(self.tested_instance < other)
Exemplo n.º 11
0
 def setUp(self):
     url_testers = []
     for _ in range(3):
         tester = Mock()
         tester.any_match.return_value = False
         tester.lookup_matching.return_value = []
         tester.filter_matching.return_value = []
         url_testers.append(tester)
     self.tested_instance = URLTesterChain(*url_testers)
Exemplo n.º 12
0
 def setUp(self):
     session_mock = Mock()
     self.head_mock = session_mock.head
     self.head_mock.side_effect = HeadSideEffects()
     self.resolve_redirects_mock = session_mock.resolve_redirects
     self.redirect_results = ResolveRedirectsSideEffects()
     self.resolve_redirects_mock.side_effect = self.redirect_results
     self.resolver = RedirectURLResolver(session_mock)
     self.patcher = patch('spam_lists.composites.is_valid_url')
     self.is_valid_url_mock = self.patcher.start()
Exemplo n.º 13
0
 def setUp(self):
     self.listed_hosts = []
     self.get_patcher = patch('spam_lists.clients.get')
     self.get_mock = self.get_patcher.start()
     self.get_mock.side_effect = create_hp_hosts_get(
         self.classification, [])
     self.host_factory_mock = Mock()
     self.tested_instance = HpHosts('spam_lists_test_suite')
     self.tested_instance._host_factory = self.host_factory_mock
     self.host_factory_mock.side_effect = host_list_host_factory
Exemplo n.º 14
0
    def test_get_urls_and_locations(self, cached_iterable_mock):
        """Test if an instance of CachedIterable is returned.

        :param cached_iterable_mock: a mock of CachedIterable
        class object
        """
        expected = Mock()
        cached_iterable_mock.return_value = expected
        actual = self.resolver.get_urls_and_locations(['http://test.com'])
        self.assertEqual(expected, actual)
Exemplo n.º 15
0
    def post(_, body):
        """Get mock of a response to a POST query to GSB Lookup API.

        :param body: a request body
        :returns: a Mock instance representing the response. Properties
        of the object depend on external values provided by the creator
        of the method: expected_401, spam_urls and classification
        """
        response = Mock()
        if expected_401:
            response.status_code = 401
            response.raise_for_status.side_effect = HTTPError
        else:
            urls = body.splitlines()[1:]
            classes = ['ok' if u not in spam_urls else
                       ','.join(classification) for u in urls]
            response.text = '\n'.join(classes)
            code = 200 if spam_urls else 204
            response.status_code = code
        return response
Exemplo n.º 16
0
    def test_lt_for_missing_to_unicode_method_to_handle(self, _, side_effect):
        """Test for TypeError when the other misses to_unicode method.

        :param side_effect: a side effect for __lt__ method of value
        attribute of the tested instance.
        """
        other = Mock(spec=['value'])
        value = MagicMock()
        value.__lt__.side_effect = side_effect
        self.tested_instance.value = value
        self.assertRaises(TypeError, self.tested_instance.__lt__, other)
Exemplo n.º 17
0
 def setUp(self):
     self.host_factory_mock = Mock()
     self.host_factory_mock.side_effect = host_list_host_factory
     classification_map = {}
     for i, k in enumerate(self.classification, 1):
         classification_map[2**i] = k
     self.tested_instance = self.dnsbl_factory('test_service',
                                               self.query_domain_str,
                                               classification_map,
                                               self.host_factory_mock)
     self.dns_query_patcher = patch('spam_lists.clients.query')
     self.dns_query_mock = self.dns_query_patcher.start()
     self.dns_query_mock.side_effect = DNSQuerySideEffects([])
Exemplo n.º 18
0
    def post(_, body):
        """Get mock of a response to a POST query to GSB Lookup API.

        :param body: a request body
        :returns: a Mock instance representing the response. Properties
        of the object depend on external values provided by the creator
        of the method: expected_401, spam_urls and classification
        """
        response = Mock()
        if expected_401:
            response.status_code = 401
            response.raise_for_status.side_effect = HTTPError
        else:
            urls = body.splitlines()[1:]
            classes = [
                'ok' if u not in spam_urls else ','.join(classification)
                for u in urls
            ]
            response.text = '\n'.join(classes)
            code = 200 if spam_urls else 204
            response.status_code = code
        return response
Exemplo n.º 19
0
    def __call__(self, query_name):
        """Query for a DNS name.

        :param query_name: a domain for which the mock is being queried
        :returns: a list containing a DNS answer mock
        :raises NXDOMAIN: if query_name is not included in
        the preconfigured list
        """
        if query_name in self.expected_query_names:
            dns_answer_mock = Mock()
            return_value = '121.0.0.{}'.format(self.last_octet)
            dns_answer_mock.to_text.return_value = return_value
            return [dns_answer_mock]
        raise NXDOMAIN
Exemplo n.º 20
0
    def test_lt_for_not_comparable_values(self):
        """Test a result of comparing non-comparable values.

        The result is expected to be equal to that of comparison of
        string values of both objects.
        """
        self.tested_instance.value.__lt__.side_effect = TypeError

        str_value = self.tested_instance.to_unicode()
        other = Mock()
        other_str_value = 'other_str'
        other.to_unicode.return_value = other_str_value

        self.assertEqual(str_value < other_str_value,
                         self.tested_instance < other)
Exemplo n.º 21
0
    def setUp(self):
        self.listed_hosts = []
        self.host_factory_mock = Mock()
        self.host_factory_mock.side_effect = host_list_host_factory
        self.tested_instance = HostList(self.host_factory_mock)
        self._contains_patcher = patch(
            'spam_lists.host_list.HostList._contains')
        self._contains_mock = self._contains_patcher.start()
        self._contains_mock.side_effect = lambda h: h in self.listed_hosts
        host_data_getter_name = (
            'spam_lists.host_list.HostList._get_match_and_classification')
        self.host_data_getter_patcher = patch(host_data_getter_name)
        self.host_data_getter_mock = self.host_data_getter_patcher.start()

        def _get_match_and_classification(host):
            if host in self.listed_hosts:
                return host, self.classification
            return None, None

        self.host_data_getter_mock.side_effect = _get_match_and_classification
Exemplo n.º 22
0
 def test_lt_for_larger_value(self):
     """Test if True is returned for a larger value."""
     self.tested_instance.value.__lt__.return_value = True
     self.assertTrue(self.tested_instance < Mock())
Exemplo n.º 23
0
 def test_constructor_for_invalid_argument(self):
     """Test if an error is raised for an invalid argument."""
     self.value_constructor_mock.side_effect = ValueError
     self.assertRaises(self.class_to_test.invalid_ip_error_type,
                       self.class_to_test, Mock())
Exemplo n.º 24
0
 def test_lt_for_smaller_value(self):
     """Test if False is returned for a smaller value."""
     self.tested_instance.value.__lt__.return_value = False
     self.assertFalse(self.tested_instance < Mock())
Exemplo n.º 25
0
 def test_lt_for_missing_value_attribute(self):
     """Test for TypeError when value misses a 'value' attribute."""
     other = Mock(spec=[])
     self.assertRaises(TypeError, self.tested_instance.__lt__, other)
Exemplo n.º 26
0
class GeneralizedURLTesterTest(unittest.TestCase):
    """Tests for GeneralizedURLTester class.

    :cvar test_urls: a list of URLs passed as argument to tested methods
    :cvar no_resolution_setup: a parameter setup for test methods
    requiring no explicit parameter to use (or not use) redirect
    resolution in tested calls. Contains names of methods of tested
    instance to be called
    :cvar common_setup: a parameter setup for test methods testing calls
    with and without redirect resolution, depending on value of
    a parameter, with False assumed as default. Contains names of
    methods of tested instance to be called.

    :ivar tested_instance: instance of GeneralizedURLTester to be
    tested
    :ivar whitelist_mock: an object representing an instance of
    a whitelist used by tested_instance
    :ivar url_tester_mock: an object representing a URL tester instance
    to be used by tested instance
    :ivar resolver_mock: an object representing an instance of
    redirect resolver to be used by tested instance
    """

    # pylint: disable=too-many-public-methods
    test_urls = ['http:abc.com', 'http://def.com', 'http://xyz.com']
    no_resolution_setup = [
        ['any_match'],
        ['filter_matching'],
        ['lookup_matching'],
    ]
    common_setup = [['any_match', True], ['filter_matching', True],
                    ['lookup_matching', True]] + no_resolution_setup

    def setUp(self):
        self.whitelist_mock = Mock()
        self.whitelist_mock.filter_matching.return_value = MagicMock()
        self.resolver_mock = Mock()
        self.resolver_mock.get_urls_and_locations.return_value = MagicMock()
        self.url_tester_mock = Mock()
        self.tested_instance = GeneralizedURLTester(self.url_tester_mock,
                                                    self.whitelist_mock,
                                                    self.resolver_mock)

    def _call_for(self, function_name, resolve_redirects):
        function = getattr(self.tested_instance, function_name)
        return function(self.test_urls, resolve_redirects)

    @parameterized.expand(common_setup)
    def test_whitelist_used_with(self, function_name, resolve_redirects=False):
        """Test if the whitelist is used during a method call.

        :param function_name: a name of a method to be tested
        :param resolve_redirects: a value of resolve_redirects argument
        of the tested method
        """
        self._call_for(function_name, resolve_redirects)
        urls_and_locations = self.test_urls
        if resolve_redirects:
            urls_and_locations = self.resolver_mock.get_urls_and_locations()
        whitelist_method = self.whitelist_mock.filter_matching
        whitelist_method.assert_called_once_with(urls_and_locations)

    @parameterized.expand(no_resolution_setup)
    def test_resolution_with(self, function_name):
        """Test if redirect resolution is performed.

        Redirect resolution must be performed during all method calls
        that receive resolve_redirects=True as argument.

        :param function_name: a name of a method to be tested
        """
        self._call_for(function_name, True)
        resolver_function = self.resolver_mock.get_urls_and_locations
        resolver_function.assert_called_once_with(self.test_urls)

    @parameterized.expand(no_resolution_setup)
    def test_no_resolution_with(self, function_name):
        """Test if redirect resolution is not performed.

        Redirect resolution must not be performed during all calls
        that receive resolve_redirects=False as argument.

        :param function_name: a name of a method to be tested
        """
        self._call_for(function_name, False)
        self.resolver_mock.assert_not_called()

    @parameterized.expand(common_setup)
    def test_url_tester_results_for(self,
                                    function_name,
                                    resolve_redirects=False):
        """Test if expected results are returned.

        Each method must return result of a method of url_tester
        called during its execution.

        :param function_name: a name of a method to be tested
        :param resolve_redirects: a value of resolve_redirects argument
        of the tested method
        """
        url_tester_function = getattr(self.url_tester_mock, function_name)
        expected = url_tester_function()
        actual = self._call_for(function_name, resolve_redirects)
        self.assertEqual(expected, actual)
Exemplo n.º 27
0
 def setUp(self):
     self.factories = tuple(Mock() for _ in range(5))