Example #1
0
    def test_return_correct_body_for_multiple_response(self):
        item1 = Mock(file_name="file1")
        item1.request = "request1"

        item2 = Mock(file_name="file2")
        item2.request = "request2"
        # item2.title = Mock(return_value="title2")

        mapper = CherryPyMapper()
        mapper.cherrypy = Mock()
        mapper.cherrypy.url = Mock(return_value="some url")

        body = log.log_multiple_matches([item1, item2])
        self.assertEqual(body, "Matched 2 items, choosing the first one\n- file1\nrequest1\n\n- file2\nrequest2\n")
Example #2
0
 def test_target_source_changed(self):
     validator = DjangoUserPermissionValidator("value")
     ctx = Mock(spec=["user"])
     ctx.request = Mock()
     ctx.request.user.has_perm.return_value = False
     self.assertFalse(validator.is_write_authorized(ctx, None, "a", "b"))
     ctx.request.user.has_perm.assert_called_with("value")
Example #3
0
    def test_widget_addform_url_on_addform(self):
        from plone.app.widgets.dx import AjaxSelectWidget

        widget = AjaxSelectWidget(self.request)
        form = Mock()
        from zope.interface import directlyProvides
        from z3c.form.interfaces import IAddForm

        directlyProvides(form, IAddForm)
        form.request = {"URL": "http://addform_url"}
        widget.form = form
        self.assertEqual(
            {"name": None, "value": u"", "pattern": "select2", "pattern_options": {"separator": ";"}},
            widget._base_args(),
        )
        widget.vocabulary = "vocabulary1"
        self.assertEqual(
            {
                "name": None,
                "value": u"",
                "pattern": "select2",
                "pattern_options": {
                    "separator": ";",
                    "vocabularyUrl": "http://addform_url/@@getVocabulary?name=vocabulary1",
                },
            },
            widget._base_args(),
        )
Example #4
0
    def test_concurrency_no_auth(self):
        lock = Lock()
        calls = set()
        items = []

        def add_item(method, url, **kwargs):
            thread = kwargs["thread"]
            with lock:
                if items:
                    other = items.pop()
                    ok_(other != thread)
                else:
                    items.append(thread)
            sleep(0.25)
            with lock:
                ok_(not items)
                calls.add(thread)
            return Mock()

        session = Mock()
        session.request = add_item
        client = KerberosClient("http://nn", max_concurrency=1, session=session)
        args = ("POST", "http://foo")
        t1 = Thread(target=client._request, args=args, kwargs={"thread": 1, "auth": True})
        t1.start()
        t2 = Thread(target=client._request, args=args, kwargs={"thread": 2})
        t2.start()
        t1.join()
        t2.join()
        eq_(calls, set([1, 2]))
    def test_should_update_state_if_available(self):
        # Set
        app = NewrelicApp("1111", "777")
        headers = {"X-Api-Key": "1111"}
        url = "/v2/applications/777.json"

        # Mocks
        connection_obj = Mock()
        response_obj = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status = 200
        response_obj.read = Mock(return_value='{"some":"json"}')
        connection_obj.connect = Mock()
        connection_obj.request = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with("GET", url, "", headers)
        connection_obj.getresponse.assert_called_once()

        self.assertEquals(app.raw_app, {"some": "json"})
        self.assertTrue(app.reachable)
Example #6
0
    def test_method_as_str(self):
        # noinspection PyShadowingNames
        def foo(_):
            pass

        # noinspection PyUnresolvedReferences
        with patch.object(MyClass, "foo", foo):
            profile_function_or_method("silk.tests.test_dynamic_profiling", "MyClass.foo", "test")
            mock_data_collector = Mock()
            mock_data_collector.queries = []
            mock_data_collector.request = Request()
            with patch("silk.profiling.profiler.DataCollector", return_value=mock_data_collector) as mock_DataCollector:
                MyClass().foo()
                self.assertEqual(mock_DataCollector.return_value.register_profile.call_count, 1)
                call_args = mock_DataCollector.return_value.register_profile.call_args[0][0]
                self.assertDictContainsSubset(
                    {
                        "func_name": foo.__name__,
                        "dynamic": True,
                        "file_path": source_file_name(),
                        "name": "test",
                        "line_num": six.get_function_code(foo).co_firstlineno,
                    },
                    call_args,
                )
    def test_should_not_update_state_if_unaavailable(self):
        # Set
        app = NewrelicApp("1111", "777")
        headers = {"X-Api-Key": "1111"}
        url = "/v2/applications/777.json"

        # Mocks
        connection_obj = Mock()
        response_obj = Mock()
        httplib.HTTPConnection = Mock(return_value=connection_obj)

        response_obj.status = 500  # Error
        response_obj.read = Mock(return_value="")
        connection_obj.connect = Mock()
        connection_obj.request = Mock()
        connection_obj.getresponse = Mock(return_value=response_obj)

        # Assertion
        app.update_state()

        connection_obj.connect.assert_called_once()
        connection_obj.request.assert_called_once_with("GET", url, "", headers)
        connection_obj.getresponse.assert_called_once()

        self.assertFalse(app.reachable)
Example #8
0
 def test_target_source_not_changed(self):
     validator = DjangoUserPermissionValidator("value")
     ctx = Mock(spec=["user"])
     ctx.request = Mock()
     # Should not call has_perm
     ctx.request.user.has_perm.side_effect = Exception
     self.assertTrue(validator.is_write_authorized(ctx, None, "a", "a"))
Example #9
0
def pytest_funcarg__response(request):
    req = request.getfuncargvalue("request")
    response = Mock()
    response.request = req
    response.request.cookie["session_key"] = "a" * 64
    response.request.session = {"session_key": "a" * 64}
    response.cookie = SimpleCookie()
    return response
Example #10
0
File: util.py Project: jvlomax/silk
def mock_data_collector():
    mock = Mock()
    mock.queries = []
    mock.local = Mock()
    r = Request()
    mock.local.request = r
    mock.request = r
    return mock
 def _dummy_send(*args, **kwargs):
     dummy_response = Mock()
     dummy_response.headers = {}
     dummy_response.status_code = status_code
     dummy_response.text = response_body
     dummy_response.request = args[0]
     _dummy_send.call_args = (args, kwargs)
     return dummy_response
Example #12
0
    def test_handle_produce_success_simple_success(self):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        response = Mock()
        response.request = Mock()
        response.request._batch = [m1]
        body = {"offsets": [{}], "value_schema_id": 1, "key_schema_id": 2}

        self.producer._handle_produce_success("test_driver", response, body)

        self.client.mock_for("produce_success").assert_called_once_with("test_driver", [(m1, {})], [])
    def _backend(self, session_kwargs=None):
        strategy = Mock()
        strategy.request = None
        strategy.session_get.return_value = object()
        strategy.partial_from_session.return_value = (0, "mock-backend", [], session_kwargs or {})

        backend = Mock()
        backend.name = "mock-backend"
        backend.strategy = strategy
        return backend
    def test_default_http_client_called(self):
        hc = Mock(stripe.http_client.HTTPClient)
        hc._verify_ssl_certs = True
        hc.name = "mockclient"
        hc.request = Mock(return_value=("{}", 200, {}))

        stripe.default_http_client = hc
        stripe.Charge.list(limit=3)

        hc.request.assert_called_with("get", "https://api.stripe.com/v1/charges?limit=3", ANY, None)
Example #15
0
    def _strategy(self, session_kwargs=None):
        backend = Mock()
        backend.name = "mock-backend"

        strategy = Mock()
        strategy.request = None
        strategy.backend = backend
        strategy.session_get.return_value = object()
        strategy.partial_from_session.return_value = (0, backend.name, [], session_kwargs or {})
        return strategy
Example #16
0
def test_submit_configuration(mock_requests):
    r = Mock()
    r.status_code = 200
    r.request = Mock()
    r.content = resource_string(__name__, "assets/test_get_job_info.xml")
    mock_requests.get.return_value = r
    r = Mock()
    r.status_code = 200
    r.request = Mock()
    mock_requests.put.return_value = r
    name = "test_submit_configuration"
    h.submit_configuration(name, "cxml")
    mock_requests.put.assert_called_with(
        url=("https://localhost:8443/engine/job/" "test/jobdir/crawler-beans.cxml"),
        data="cxml",
        auth=None,
        verify=False,
        headers={"accept": "application/xml"},
        timeout=None,
    )
Example #17
0
    def test_dynamic_decorator(self):
        middleware = SilkyMiddleware()
        SilkyConfig().SILKY_DYNAMIC_PROFILING = [{"module": "silk.tests.data.dynamic", "function": "foo"}]
        middleware._apply_dynamic_mappings()
        from silk.tests.data.dynamic import foo

        mock = Mock()
        mock.queries = []
        mock.request = Request()
        with patch("silk.profiling.profiler.DataCollector", return_value=mock) as mock_DataCollector:
            foo()  # Should be wrapped in a decorator
            self.assertTrue(mock_DataCollector.return_value.register_profile.call_count)
Example #18
0
    def test_handle_produce_response_transport_error(self, fake_retry):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        response = Mock()
        response.code = 599
        response.error = object()
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1

        self.producer._handle_produce_response("test_driver", response)

        self.client.mock_for("response_5xx").assert_called_once_with("test_driver", response)
        fake_retry.assert_has_calls([call("test_driver", m1), call("test_driver", m2)])
Example #19
0
def test_get_info(mock_requests):
    r = Mock()
    r.status_code = 200
    r.content = resource_string(__name__, "assets/test_get_info.xml")
    r.request = Mock()
    mock_requests.get.return_value = r
    info = h.get_info()
    mock_requests.get.assert_called_with(
        url="https://localhost:8443/engine",
        auth=None,
        verify=False,
        headers={"accept": "application/xml"},
        timeout=None,
    )
    assert_equals("3.1.1", info["engine"]["heritrixVersion"])
Example #20
0
def test_rescan_job_directory(mock_requests):
    r = Mock()
    r.status_code = 303
    r.request = Mock()
    mock_requests.post.return_value = r
    h.rescan_job_directory()
    mock_requests.post.assert_called_with(
        url="https://localhost:8443/engine",
        data=dict(action="rescan"),
        auth=None,
        verify=False,
        headers={"accept": "application/xml"},
        allow_redirects=False,
        timeout=None,
    )
Example #21
0
    def test_handle_produce_response_on_200(self, fake_decode, fake_handle_success):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        response = Mock()
        response.code = 200
        response.error = False
        response.request = Mock()
        response.request._batch = [m1, m2]
        response.request._id = 1
        body = {"offsets": [{}, {}], "value_schema_id": 1, "key_schema_id": 2}
        fake_decode.return_value = body

        self.producer._handle_produce_response("test_driver", response)

        fake_handle_success.assert_called_once_with("test_driver", response, body)
Example #22
0
    def test_validates_the_request(self):
        """Validates the request against CSRF attacks."""

        from ..csrf import validate_against_csrf

        mock_request = Mock()
        mock_request.registry.settings = {}
        mock_validator = Mock()
        mock_validator_factory = Mock()
        mock_validator_factory.return_value = mock_validator
        mock_event = Mock()
        mock_event.request = mock_request

        validate_against_csrf(mock_event, Validator=mock_validator_factory)
        mock_validator.validate.assert_called_with(mock_request)
Example #23
0
def test_create_job(mock_requests):
    r = Mock()
    r.status_code = 303
    r.request = Mock()
    mock_requests.post.return_value = r
    name = "test_create_job"
    h.create_job(name)
    mock_requests.post.assert_called_with(
        url="https://localhost:8443/engine",
        data=dict(action="create", createpath=name),
        auth=None,
        verify=False,
        headers={"accept": "application/xml"},
        allow_redirects=False,
        timeout=None,
    )
Example #24
0
def test_get_job_info(mock_requests):
    r = Mock()
    r.status_code = 200
    r.content = resource_string(__name__, "assets/test_get_job_info.xml")
    r.request = Mock()
    mock_requests.get.return_value = r
    name = "test_get_job_info"
    info = h.get_job_info(name)
    mock_requests.get.assert_called_with(
        url="https://localhost:8443/engine/job/%s" % name,
        auth=None,
        verify=False,
        headers={"accept": "application/xml"},
        timeout=None,
    )
    assert_equals("test", info["job"]["shortName"])
Example #25
0
def test_copy_job_as_profile(mock_requests):
    r = Mock()
    r.status_code = 303
    r.request = Mock()
    mock_requests.post.return_value = r
    src_name = "test_copy_job"
    dest_name = "test_copy_job_copy"
    h.copy_job(src_name, dest_name, as_profile=True)
    mock_requests.post.assert_called_with(
        url="https://localhost:8443/engine/job/%s" % src_name,
        data=dict(copyTo=dest_name, asProfile="on"),
        auth=None,
        verify=False,
        headers={"accept": "application/xml"},
        allow_redirects=False,
        timeout=None,
    )
Example #26
0
def test_supply_timeout(mock_requests):
    h = hapy.Hapy(BASE_URL, timeout=0.005)
    r = Mock()
    r.status_code = 303
    r.request = Mock()
    mock_requests.post.return_value = r
    name = "test_build_job"
    h.build_job(name)
    mock_requests.post.assert_called_with(
        url="https://localhost:8443/engine/job/%s" % name,
        data=dict(action="build"),
        auth=None,
        verify=False,
        headers={"accept": "application/xml"},
        allow_redirects=False,
        timeout=0.005,
    )
Example #27
0
    def test_doesnt_validate_the_request(self):
        """Only validates the request against CSRF attacks if settings['csrf_validate']
          isn't false.
        """

        from ..csrf import validate_against_csrf

        mock_request = Mock()
        mock_request.registry.settings = {"csrf.validate": False}
        mock_validator = Mock()
        mock_validator_factory = Mock()
        mock_validator_factory.return_value = mock_validator
        mock_event = Mock()
        mock_event.request = mock_request

        validate_against_csrf(mock_event, Validator=mock_validator_factory)
        self.assertRaises(AssertionError, mock_validator.validate.assert_called_with, mock_request)
Example #28
0
 def make_response(self, response_attrs=None, request_attrs=None):
     response = Mock()
     request = Mock()
     response.code = 200
     response.error = None
     response.body = json.dumps({"offsets": [{}]})
     request._id = 1
     request._topic = "test_driver"
     request._batch = [Message("test_driver", self.test_value, None, None, 0, 1)]
     for k, v in (response_attrs or {}).items():
         if k == "body":
             v = json.dumps(v)
         setattr(response, k, v)
     for k, v in (request_attrs or {}).items():
         setattr(request, k, v)
     response.request = request
     return response
Example #29
0
    def test_handle_produce_success_mixed_success(self, fake_retry):
        m1 = Message("test_driver", {"val": 1}, None, None, 0, 1)
        m2 = Message("test_driver", {"val": 2}, None, None, 0, 1)
        m3 = Message("test_driver", {"val": 3}, None, None, 0, 1)
        offsets = [{}, {"error_code": 1, "message": "Nonretriable"}, {"error_code": 2, "message": "Retriable"}]
        response = Mock()
        response.request = Mock()
        response.request._batch = [m1, m2, m3]
        response.request._id = 1
        body = {"offsets": offsets, "value_schema_id": 1, "key_schema_id": 2}

        self.producer._handle_produce_success("test_driver", response, body)

        self.client.mock_for("produce_success").assert_called_once_with(
            "test_driver", [(m1, {})], [(m2, offsets[1]), (m3, offsets[2])]
        )
        self.client.mock_for("drop_message").assert_called_once_with("test_driver", m2, "nonretriable")
        fake_retry.assert_called_once_with("test_driver", m3)
Example #30
0
    def test_single_strategy(self):
        """ A single transform supplied.

            @transforms(gzip)
            get(self):
                ...
        """
        from wheezy.web.transforms import handler_transforms

        def transform(request, response):
            assert "request" == request
            return response + "-transformed"

        mock_handler = Mock()
        mock_handler.request = "request"
        mock_handler_method = Mock(return_value="response")
        handler = handler_transforms(transform)(mock_handler_method)
        assert "response-transformed" == handler(mock_handler)