Example #1
0
    def test_any_mock_calls_comparison_order(self):
        mock = Mock()
        d = datetime.now()

        class Foo(object):
            def __eq__(self, other):
                return False

            def __ne__(self, other):
                return True

        for d in datetime.now(), Foo():
            mock.reset_mock()

            mock(d, foo=d, bar=d)
            mock.method(d, zinga=d, alpha=d)
            mock().method(a1=d, z99=d)

            expected = [
                call(ANY, foo=ANY, bar=ANY),
                call.method(ANY, zinga=ANY, alpha=ANY),
                call(),
                call().method(a1=ANY, z99=ANY),
            ]
            self.assertEqual(expected, mock.mock_calls)
            self.assertEqual(mock.mock_calls, expected)
Example #2
0
def test_mock_assert_called_with_can_fail():
    test_object = Mock()

    test_object.method({"bob": "barker"})

    with pytest.raises(AssertionError):
        test_object.method.assert_called_with(instance_of(list))
Example #3
0
    def test_serverCreate(self):
        mock = Mock()
        mock.method = Mock(return_value=True)
        actual = mock.method()
        expected = True

        self.assertEqual(actual, expected)
Example #4
0
    def test_clientRead(self):
        mock = Mock()
        mock.method = Mock(return_value=True)

        actual = mock.method()
        expected = True

        self.assertEqual(actual, expected)
Example #5
0
    def test_mock_method_calls(self):
        mock = Mock()
        mock()
        mock.method().attribute.method()
        mock.attribute.method()

        # mock_calls: inclusive, recursive; split by '()', good for callable mocks.
        self.assertEqual(
            mock.mock_calls, [call(), call.method(), call.method().attribute.method(), call.attribute.method()]
        )

        # method_calls: exclusive, recursive; terminated by '()', good for non-callable mocks.
        self.assertEqual(mock.method_calls, [call.method(), call.attribute.method()])
Example #6
0
    def test_deny_create_on_put_permission(self):
        permission = DenyCreateOnPutPermission()
        view = Mock()
        request = Mock()

        request.method = "GET"
        self.assertTrue(permission.has_permission(request, view))

        request.method = "PUT"
        self.assertTrue(permission.has_permission(request, view))

        request.method = "PUT"
        view.get_object = Mock(side_effect=Http404)
        self.assertFalse(permission.has_permission(request, view))
 def setUp(self):
     request = Mock()
     request.method = "POST"
     request.POST = {"livetranslation-popup-0-msgid": "the-msgid", "livetranslation-popup-0-en": "the-msgstr"}
     with patch("livetranslation.views.save_translations") as save:
         self.response = get_translations(request)
     self.save_translations = save
 def setUp(self):
     request = Mock()
     request.method = "GET"
     request.GET = {"msgid": "the-msgid"}
     get_all_translations = Mock(return_value={"dummy": "json"})
     with patch("livetranslation.views.get_all_translations", get_all_translations):
         self.response = get_translations(request)
Example #9
0
def requestMock(path, method="GET", host="localhost", port=8080, isSecure=False):
    postpath = path.split("/")

    request = Mock()
    request.getRequestHostname.return_value = host
    request.getHost.return_value.port = port
    request.postpath = postpath
    request.prepath = []
    request.method = method
    request.isSecure.return_value = isSecure
    request.notifyFinish.return_value = Deferred()
    request.finished = False
    request.__klein_branch_segments__ = []

    def render(resource):
        return _render(resource, request)

    def finish():
        request.notifyFinish.return_value.callback(None)
        request.finished = True

    def processingFailed(failure):
        request.failed = failure
        request.notifyFinish.return_value.errback(failure)

    request.finish.side_effect = finish
    request.render.side_effect = render
    request.processingFailed.side_effect = processingFailed

    return request
Example #10
0
 def has_object_perm(self, auth, user, obj, method="GET"):
     perm = ProjectPermission()
     request = Mock()
     request.auth = auth
     request.user = user
     request.method = method
     return perm.has_object_permission(request, None, obj)
Example #11
0
 def has_perm(self, method, obj, auth=None, user=None):
     perm = TeamPermission()
     request = Mock()
     request.auth = auth
     request.user = user
     request.method = method
     return perm.has_object_permission(request, None, obj)
Example #12
0
def test_api_resource():
    """
    Test APIResource class
    """
    resource = pdrest.APIResource()
    resource.register("method", "method", do_nothing)

    request = Mock()

    request.method = "method"
    request.path = "method"
    result = resource._get_callback(request)
    assert result[0] == do_nothing

    resource.getChild("method", request)

    resource.unregister(regex="method")

    # After unregister, the callback should be gone.
    result = resource._get_callback(request)
    assert result[0] is None

    resource.getChild("method", request)

    resource.children = Mock(name="what")
    result = resource.getChild("method", request)
    resource.getChild("method", request)
 def test_process_request_empty_header(self):
     request = Mock(path="/")
     request.method = "OPTIONS"
     request.META = {"HTTP_ACCESS_CONTROL_REQUEST_METHOD": ""}
     with settings_override(CORS_URLS_REGEX="^.*$"):
         response = self.middleware.process_request(request)
     self.assertIsInstance(response, HttpResponse)
    def test_process_view_replace_https_referer(self):
        post_middleware = CorsPostCsrfMiddleware()
        request = Mock(path="/")
        request.method = "GET"
        request.is_secure = lambda: True
        request.META = {
            "HTTP_REFERER": "https://foo.google.com/",
            "HTTP_HOST": "foobar.com",
            "HTTP_ORIGIN": "https://foo.google.com",
        }
        with settings_override(
            CORS_URLS_REGEX="^.*$", CORS_ORIGIN_REGEX_WHITELIST=".*google.*", CORS_REPLACE_HTTPS_REFERER=True
        ):
            response = self.middleware.process_view(request, None, None, None)
        self.assertIsNone(response)
        self.assertEquals(request.META["ORIGINAL_HTTP_REFERER"], "https://foo.google.com/")
        self.assertEquals(request.META["HTTP_REFERER"], "https://foobar.com/")

        with settings_override(CORS_URLS_REGEX="^.*$", CORS_REPLACE_HTTPS_REFERER=True):
            post_middleware.process_view(request, None, None, None)
        self.assertTrue("ORIGINAL_HTTP_REFERER" not in request.META)
        self.assertEquals(request.META["HTTP_REFERER"], "https://foo.google.com/")

        with settings_override(CORS_URLS_REGEX="^.*$", CORS_REPLACE_HTTPS_REFERER=True):
            response = post_middleware.process_view(request, None, None, None)
        self.assertIsNone(response)
Example #15
0
    def test_login_and_store_credentials_in_session(self):
        # only testing custom logic, which happens on POST
        # everything else is handled by django.contrib.auth
        mockrequest = Mock()
        mockrequest.method = "POST"

        def not_logged_in(rqst):
            rqst.user.is_authenticated.return_value = False

        def set_logged_in(rqst):
            rqst.user.is_authenticated.return_value = True
            rqst.POST.get.return_value = "TEST_PASSWORD"

        # failed login
        with patch("eulfedora.views.authviews.login", new=Mock(side_effect=not_logged_in)):
            mockrequest.session = dict()
            response = login_and_store_credentials_in_session(mockrequest)
            self.assert_(
                FEDORA_PASSWORD_SESSION_KEY not in mockrequest.session,
                "user password for fedora should not be stored in session on failed login",
            )

        # successful login
        with patch("eulfedora.views.authviews.login", new=Mock(side_effect=set_logged_in)):
            response = login_and_store_credentials_in_session(mockrequest)
            self.assert_(
                FEDORA_PASSWORD_SESSION_KEY in mockrequest.session,
                "user password for fedora should be stored in session on successful login",
            )
            # test password stored in the mock request
            pwd = mockrequest.POST.get()
            # encrypted password stored in session
            sessionpwd = mockrequest.session[FEDORA_PASSWORD_SESSION_KEY]
            self.assertNotEqual(pwd, sessionpwd, "password should not be stored in the session without encryption")
            self.assertEqual(pwd, cryptutil.decrypt(sessionpwd), "user password stored in session is encrypted")
 def test_get_bounding_box_of_country(self):
     request = Mock()
     request.method = "GET"
     request.GET.get.return_value = MockGeoserver().response()
     geonames_service = Mock()
     geoserver = Mock()
     geoserver.get_admin_units_for_country.return_value = '["Districts", "County"]'
     geonames_service.query_for_country.return_value = """
                                                       {"geonames"
                                                       :[{"countryName":"India",
                                                          "bBoxWest":68.1866760253906,
                                                          "currencyCode":"INR",
                                                          "fipsCode":"IN",
                                                          "countryCode":"IN",
                                                          "isoNumeric":"356",
                                                          "capital":"New Delhi",
                                                          "areaInSqKm":"3287590.0",
                                                          "languages":"en-IN,hi,bn,te,mr,ta,ur,gu,ml,kn,or,pa,as,ks,sd,sa,ur-IN",
                                                          "bBoxEast":97.4033126831055,
                                                          "isoAlpha3":"IND",
                                                          "continent":"AS",
                                                          "bBoxNorth":35.5042304992676,
                                                          "geonameId":1269750,
                                                          "bBoxSouth":6.74713850021362,
                                                          "population":"1147995000"}]}"""
     response = views.country_details(request, geonames_service, geoserver)
     self.assertEquals(
         '{"north": 180, "west": -90, "admin_units": "", "country": "Request failed", "east": 90, "adm1": [], "south": -180}',
         response.content,
     )
Example #17
0
    def prepare_request_mock(
        self,
        data,
        referer="http://localhost/user_with_workspaces/Public Workspace",
        user=None,
        extra_headers={},
        GET="",
    ):
        request = Mock()
        request.method = "POST"
        request.get_host.return_value = "localhost"
        GET_PARAMETERS = parse_qsl(GET)
        request.GET = MagicMock()
        request.GET.__len__.side_effect = lambda: len(GET_PARAMETERS)
        request.GET.__getitem__.side_effect = lambda key: GET_PARAMETERS[key]
        request.GET.urlencode.side_effect = lambda: GET
        request.COOKIES = {settings.SESSION_COOKIE_NAME: "test"}
        request.META = {
            "HTTP_ACCEPT": "application/json",
            "SERVER_PROTOCOL": "http",
            "REMOTE_ADDR": "127.0.0.1",
            "content_type": "application/json",
            "content_length": len(data),
            "HTTP_HOST": "localhost",
            "HTTP_REFERER": referer,
            "HTTP_X_FI_WARE_OAUTH_TOKEN": "true",
        }
        request.META.update(extra_headers)
        request.read.return_value = data
        if user is None:
            request.user = self.admin_mock
        else:
            request.user = user

        return request
Example #18
0
def test_fakesock_socket_sendall_with_body_data_with_chunked_entry(POTENTIAL_HTTP_PORTS, old_socket, match_uriinfo):
    ("fakesock.socket#sendall should call real_sendall when not ")
    # Background:
    # Using a subclass of socket that mocks out real_sendall

    class MySocket(fakesock.socket):
        def real_sendall(self, data):
            raise AssertionError("should have never been called")

    matcher = Mock(name="matcher")
    info = Mock(name="info")
    httpretty.match_uriinfo.return_value = (matcher, info)

    # Using a mocked entry
    entry = Mock()
    entry.method = "GET"
    entry.info.path = "/foo"

    entry.request.headers = {"transfer-encoding": "chunked"}
    entry.request.body = b""

    # Given an instance of that socket
    socket = MySocket()
    socket._entry = entry

    # And that is is considered http
    socket.connect(("foo.com", 80))

    # When I try to send data
    socket.sendall(b"BLABLABLABLA")

    # Then the entry should have that body
    httpretty.last_request.body.should.equal(b"BLABLABLABLA")
Example #19
0
    def get_signed_grade_mock_request_with_correct_signature(self):
        """
        Generate a proper LTI request object
        """
        mock_request = Mock()
        mock_request.headers = {
            "X-Requested-With": "XMLHttpRequest",
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": (
                u'OAuth realm="https://testurl/", oauth_body_hash="wwzA3s8gScKD1VpJ7jMt9b%2BMj9Q%3D",'
                'oauth_nonce="18821463", oauth_timestamp="1409321145", '
                'oauth_consumer_key="__consumer_key__", oauth_signature_method="HMAC-SHA1", '
                'oauth_version="1.0", oauth_signature="fHsE1hhIz76/msUoMR3Lyb7Aou4%3D"'
            ),
        }
        mock_request.url = u"https://testurl"
        mock_request.http_method = u"POST"
        mock_request.method = mock_request.http_method

        mock_request.body = (
            "<?xml version='1.0' encoding='utf-8'?>\n"
            '<imsx_POXEnvelopeRequest xmlns="http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">'
            "<imsx_POXHeader><imsx_POXRequestHeaderInfo><imsx_version>V1.0</imsx_version>"
            "<imsx_messageIdentifier>edX_fix</imsx_messageIdentifier></imsx_POXRequestHeaderInfo>"
            "</imsx_POXHeader><imsx_POXBody><replaceResultRequest><resultRecord><sourcedGUID>"
            "<sourcedId>MITxLTI/MITxLTI/201x:localhost%3A8000-i4x-MITxLTI-MITxLTI-lti-3751833a214a4f66a0d18f63234207f2:363979ef768ca171b50f9d1bfb322131</sourcedId>"  # pylint: disable=line-too-long
            "</sourcedGUID><result><resultScore><language>en</language><textString>0.32</textString></resultScore>"
            "</result></resultRecord></replaceResultRequest></imsx_POXBody></imsx_POXEnvelopeRequest>"
        )

        return mock_request
Example #20
0
    def prepare_request_mock(
        self,
        data=None,
        referer="http://localhost/user_with_workspaces/Public Workspace",
        user=None,
        extra_headers={},
        GET="",
        use_deprecated_code=False,
    ):

        request = Mock()
        request.get_host.return_value = "localhost"
        GET_PARAMETERS = parse_qsl(GET)
        request.GET = MagicMock()
        request.GET.__len__.side_effect = lambda: len(GET_PARAMETERS)
        request.GET.__getitem__.side_effect = lambda key: GET_PARAMETERS[key]
        request.GET.urlencode.side_effect = lambda: GET
        request.COOKIES = {settings.SESSION_COOKIE_NAME: "test"}
        request.META = {
            "HTTP_ACCEPT": "application/json",
            "SERVER_PROTOCOL": "http",
            "REMOTE_ADDR": "127.0.0.1",
            "HTTP_HOST": "localhost",
            "HTTP_REFERER": referer,
        }
        if data is not None:
            request.method = "POST"
            data = data.encode("utf-8")
            request.META["content_type"] = "application/json"
            request.META["content_length"] = len(data)
            request.read.return_value = data
        else:
            request.method = "GET"

        if use_deprecated_code:
            request.META["HTTP_X_FI_WARE_OAUTH_TOKEN"] = "true"
            extra_headers = {self.deprecation_mapping[key]: value for key, value in six.iteritems(extra_headers)}
        else:
            request.META["HTTP_FIWARE_OAUTH_TOKEN"] = "true"

        request.META.update(extra_headers)
        if user is None:
            request.user = self.admin_mock
        else:
            request.user = user

        return request
Example #21
0
 def has_object_perm(self, method, obj, auth=None, user=None, is_superuser=None):
     perm = TeamPermission()
     request = Mock()
     request.auth = auth
     request.user = user
     request.method = method
     request.is_superuser = lambda: is_superuser if is_superuser is not None else user.is_superuser
     return perm.has_object_permission(request, None, obj)
    def test_validate_post_notsupported(self):
        """This test case ensures creation of new persons through api always fails."""

        request = Mock()
        request.method = "POST"

        with self.assertRaises(FantasticoRoaMethodNotSupportedError):
            self._validator.validate({}, request)
Example #23
0
    def test_method_must_have_side_effects(self):
        """Method must have side effects."""

        from ..csrf import CSRFError

        mock_request = Mock()
        mock_request.method = "b"

        validator = self.makeOne("token", target_methods=["a"])
        retval = validator.validate(mock_request)

        self.assertTrue(retval is None)
        self.assertRaises(AssertionError, mock_request.headers.get.assert_called_with, "X-Requested-With")

        mock_request = Mock()
        mock_request.method = "a"
        self.assertRaises(CSRFError, validator.validate, mock_request)
Example #24
0
    def test_login_redirect_invalid_method(self):

        request = Mock()
        request.META = {}
        request.method = "POST"
        request.session.get.return_value = None
        response = login(request)
        self.assertEqual(response.status_code, 405)
Example #25
0
 def test_trap_duplicate_skipped_on_standalone(self, trap_duplicate_mock):
     self.create_switch("webapps-unique-by-domain")
     request = Mock()
     request.method = "POST"
     request.POST = {"manifest": ""}
     request.return_value = collections.namedtuple("FakeResponse", "status_code content")
     standalone_hosted_upload(request)
     assert not trap_duplicate_mock.called
Example #26
0
def mock_request(method="subtract", args=None, kwargs=None):
    mock_request = Mock(RPCRequest)
    mock_request.method = method
    mock_request.args = args or [4, 6]
    mock_request.kwargs = kwargs or {}
    mock_request.respond = Mock(RPCRequest.respond)
    mock_request.error_respond = Mock(RPCRequest.error_respond)

    return mock_request
 def test_admin_units(self):
     geoServer = MockGeoServer()
     request = Mock()
     request.method = "GET"
     request.GET.get.return_value = geoServer.get_feature_info()
     httpResponse = search_admin_units(request)
     self.assertTrue(
         '{"infrastructure": "", "name": "Gulu", "country": "Uganda", "governance": "", "dev_partners": "", "environment": "", "recent_reports": "", "health": "", "social_sector": "", "region_type": "District", "found": true, "agriculture": "", "id": 1, "resources": "", "economy": ""}',
         httpResponse.content,
     )
Example #28
0
    def test_force_to_lowercase(self):
        """Method name is forced to lower case."""

        from ..csrf import CSRFError

        mock_request = Mock()
        mock_request.method = "A"

        validator = self.makeOne("token", target_methods=["a"])
        self.assertRaises(CSRFError, validator.validate, mock_request)
    def test_setup_queue(self):
        result = Mock()
        result.method = Mock()
        result.method.queue = Mock()
        self.channel.queue_declare.return_value = result

        self._new_transport()

        self.channel.queue_declare.assert_called_once_with(exclusive=True)
        self.channel.basic_consume.assert_called_once_with(ANY, no_ack=True, queue=result.method.queue)
Example #30
0
 def test_max_request(self):
     SilkyConfig().SILKY_MAX_REQUEST_BODY_SIZE = 10  # 10kb
     mock_request = Mock()
     mock_request.META = {"CONTENT_TYPE": "text/plain"}
     mock_request.GET = {}
     mock_request.method = "get"
     mock_request.body = "a".encode("ascii") * 1024 * 100  # 100kb
     mock_request.path = reverse("silk:requests")
     request_model = RequestModelFactory(mock_request).construct_request_model()
     self.assertFalse(request_model.raw_body)