示例#1
0
    def testPUTSetOfStringsNotAllStrings(self):
        """
        PUT a set of strings (that are in fact not all strings) value for
        ntoll/rating onto the object about africa. This should result in a
        BAD_REQUEST status and an UnsupportedJSONType error class.
        """
        about = 'africa'
        tag = 'ntoll/rating'
        tagset = ['good', 'bad', 6]
        objectIdAboutAfrica = util.generateObjectId()
        fakeQueryResolver = FakeQueryResolver(about, [objectIdAboutAfrica],
                                              self)
        fakeTagsClient = FakeTagsClient()
        facadeClient = FakeFacadeClient(fakeTagsClient=fakeTagsClient,
                                        fakeQueryResolver=fakeQueryResolver)
        session = FakeSession()
        resource = AboutTagInstanceResource(facadeClient, session, about, tag)

        # Test PUT.
        payload = json.dumps(tagset)
        headers = {
            'Content-Length': [str(len(payload))],
            'Content-Type': [contentTypeForPrimitiveJSON],
        }
        d = defer.Deferred()
        request = FakeRequest('PUT', d, headers)
        request.content = StringIO.StringIO(payload)
        resource.render(request)
        yield d
        self.assertEqual(request.status, http.BAD_REQUEST)
        self.assertEqual(request.getResponseHeader(buildHeader('Error-Class')),
                         error.UnsupportedJSONType.__name__)
示例#2
0
    def testContentMD5OK(self):
        """
        Checks that an incoming requests whose payload matches the
        Content-MD5 header.
        """

        payload = {"description": "A namespace for tags that I'm using to"
                                  " add to people",
                   "name": "people"}
        content = json.dumps(payload)
        contentLength = len(content)
        md5Content = base64.standard_b64encode(md5(content).digest())
        request = http.Request(DummyChannel(), False)
        request.method = 'POST'
        request.requestHeaders.setRawHeaders("Content-MD5", [md5Content])
        request.requestHeaders.setRawHeaders("Content-Length",
                                             [str(contentLength)])
        request.requestHeaders.setRawHeaders("Content-Type",
                                             ["application/json"])
        request.requestHeaders.setRawHeaders("Host",
                                             ["fluiddb.fluidinfo.com"])
        request._fluidDB_reqid = 'xxx'
        request.args = dict()
        request.postpath = []
        request.content = StringIO(content)

        resource = NamespacesResource(FakeFacadeClient(), FakeSession())
        resource.render(request)
        self.assertEqual(request.code, http.CREATED)
示例#3
0
    def testPUTWithNoContentTypeButWithPayload(self):
        """
        Check that if we attempt a PUT with a payload but don't send a
        Content-Type, we get a BAD_REQUEST response and a
        NoContentTypeHeader response error-class header.
        """
        about = 'africa'
        tag = 'ntoll/binary'
        payload = 'random payload'
        objectIdAboutAfrica = util.generateObjectId()
        fakeQueryResolver = FakeQueryResolver(about, [objectIdAboutAfrica],
                                              self)
        fakeTagsClient = FakeTagsClient()
        facadeClient = FakeFacadeClient(fakeTagsClient=fakeTagsClient,
                                        fakeQueryResolver=fakeQueryResolver)
        session = FakeSession()
        resource = AboutTagInstanceResource(facadeClient, session, about, tag)

        # Test PUT.
        headers = {
            'Content-Length': [str(len(payload))],
        }
        d = defer.Deferred()
        request = FakeRequest('PUT', d, headers)
        request.content = StringIO.StringIO(payload)
        resource.render(request)
        yield d
        self.assertEqual(request.status, http.BAD_REQUEST)
        self.assertEqual(request.getResponseHeader(buildHeader('Error-Class')),
                         error.NoContentTypeHeader.__name__)
示例#4
0
 def testCorsHeadersDoNotAppearForRegularRequests(self):
     """
     Make sure CORS related headers do NOT appear in regular non-CORS
     requests
     """
     payload = {
         'description': 'A namespace for tags I add to people',
         'name': 'people'
     }
     content = json.dumps(payload)
     contentLength = len(content)
     request = http.Request(DummyChannel(), False)
     request.method = 'POST'
     request.requestHeaders.setRawHeaders('Content-Length',
                                          [str(contentLength)])
     request.requestHeaders.setRawHeaders('Content-Type',
                                          ['application/json'])
     request.requestHeaders.setRawHeaders('Host', ['fluiddb.fluidinfo.com'])
     request._fluidDB_reqid = 'xxx'
     request.args = dict()
     request.postpath = []
     request.content = StringIO(content)
     resource = NamespacesResource(FakeFacadeClient(), FakeSession())
     resource.render(request)
     # 201 Created
     self.assertEqual(request.code, http.CREATED)
     # check we don't have the CORS related headers
     headers = request.responseHeaders
     self.assertFalse(headers.hasHeader('Access-Control-Allow-Origin'))
     self.assertFalse(headers.hasHeader('Access-Control-Allow-Credentials'))
     self.assertFalse(headers.hasHeader('Access-Control-Expose-Headers'))
示例#5
0
 def testRegularCORSHeaders(self):
     """
     Validates that the headers are handled correctly for a CORS request
     that doesn't use the OPTIONS verb
     """
     # The origin to use in the tests
     dummyOrigin = 'http://foo.com'
     expectedHeaders = [
         'X-FluidDB-Error-Class', 'X-FluidDB-Path', 'X-FluidDB-Message',
         'X-FluidDB-ObjectId', 'X-FluidDB-Name', 'X-FluidDB-Category',
         'X-FluidDB-Action', 'X-FluidDB-Rangetype', 'X-FluidDB-Fieldname',
         'X-FluidDB-Argument', 'X-FluidDB-Access-Token',
         'X-FluidDB-Username', 'X-FluidDB-New-User'
     ]
     payload = {
         'description': 'A namespace for tags that I add to people',
         'name': 'people'
     }
     content = json.dumps(payload)
     contentLength = len(content)
     request = http.Request(DummyChannel(), False)
     request.method = 'POST'
     request.requestHeaders.setRawHeaders('Content-Length',
                                          [str(contentLength)])
     request.requestHeaders.setRawHeaders('Content-Type',
                                          ['application/json'])
     request.requestHeaders.setRawHeaders('Host', ['fluiddb.fluidinfo.com'])
     request.requestHeaders.setRawHeaders('Origin', [dummyOrigin])
     request._fluidDB_reqid = 'xxx'
     request.args = dict()
     request.postpath = []
     request.content = StringIO(content)
     resource = NamespacesResource(FakeFacadeClient(), FakeSession())
     resource.render(request)
     # 201 Created
     self.assertEqual(request.code, http.CREATED)
     # check we have the required headers
     headers = request.responseHeaders
     self.assertTrue(headers.hasHeader('Access-Control-Allow-Origin'))
     self.assertTrue(headers.hasHeader('Access-Control-Allow-Credentials'))
     self.assertTrue(headers.hasHeader('Access-Control-Expose-Headers'))
     # check the values of the required headers
     self.assertEqual(
         dummyOrigin,
         headers.getRawHeaders('Access-Control-Allow-Origin')[0])
     self.assertEqual(
         'true',
         headers.getRawHeaders('Access-Control-Allow-Credentials')[0])
     accessControlExposeHeaders = headers.getRawHeaders(
         'Access-Control-Expose-Headers')[0]
     # Make sure we haven't accidentally turned the header value into a
     # Python tuple by including a comma in its definition.
     self.assertTrue(isinstance(accessControlExposeHeaders, str))
     # Make sure we haven't accidentally left a comma space in the last
     # element of the Python header definition.
     self.assertFalse(accessControlExposeHeaders.endswith(', '))
     actualHeaders = accessControlExposeHeaders.split(', ')
     for header in expectedHeaders:
         self.assertTrue(header.startswith('X-FluidDB-'))
         self.assertTrue(header in actualHeaders)
示例#6
0
    def testInvalidCORSPreFlightRequestNoACRM(self):
        """
        The request has an Origin header but no
        Access-Control-Request-Method so check it returns a regular OPTIONS
        response.
        """
        # The origin to use in the tests
        dummyOrigin = 'http://foo.com'

        request = http.Request(DummyChannel(), False)
        request.method = 'OPTIONS'
        request.requestHeaders.setRawHeaders('Origin', [dummyOrigin])
        request._fluidDB_reqid = 'xxx'
        request.args = dict()
        request.postpath = []
        request.content = NoContent()
        resource = NamespacesResource(FakeFacadeClient(), FakeSession())
        resource._handleOptions(request, dummyOrigin)
        # 200 OK
        self.assertEqual(request.code, http.OK)
        # check we have the required headers
        headers = request.responseHeaders
        self.assertTrue(headers.hasHeader('Allow'))
        # Check the allowed methods (including and in addition to those
        # allowed for CORS)
        allowedMethods = headers.getRawHeaders('Allow')[0].split(', ')
        self.assertEqual(len(resource.allowedMethods), len(allowedMethods))
        for item in resource.allowedMethods:
            self.assertTrue(item in allowedMethods)
        # There are *NO* CORS related headers
        self.assertFalse(headers.hasHeader('Access-Control-Allow-Origin'))
        self.assertFalse(headers.hasHeader('Access-Control-Max-Age'))
        self.assertFalse(headers.hasHeader('Access-Control-Allow-Credentials'))
        self.assertFalse(headers.hasHeader('Access-Control-Allow-Methods'))
示例#7
0
 def testRegularOptionsCall(self):
     """
     Validates that a regular non-CORS OPTIONS call returns an appropriate
     response
     """
     request = http.Request(DummyChannel(), False)
     request.method = 'OPTIONS'
     request._fluidDB_reqid = 'xxx'
     request.args = dict()
     request.postpath = []
     request.content = NoContent()
     resource = NamespacesResource(FakeFacadeClient(), FakeSession())
     resource._handleOptions(request, None)
     # 200 OK
     self.assertEqual(request.code, http.OK)
     # check we have the required headers
     headers = request.responseHeaders
     self.assertTrue(headers.hasHeader('Allow'))
     # Check the allowed methods (including and in addition to those
     # allowed for CORS)
     allowedMethods = headers.getRawHeaders('Allow')[0].split(', ')
     self.assertEqual(len(resource.allowedMethods), len(allowedMethods))
     for item in resource.allowedMethods:
         self.assertTrue(item in allowedMethods)
     # There are *NO* CORS related headers
     self.assertFalse(headers.hasHeader('Access-Control-Allow-Origin'))
     self.assertFalse(headers.hasHeader('Access-Control-Max-Age'))
     self.assertFalse(headers.hasHeader('Access-Control-Allow-Credentials'))
     self.assertFalse(headers.hasHeader('Access-Control-Allow-Methods'))
示例#8
0
    def assertXFluidDBHeaderForType(self, method, value, expectedTypeString):
        """
        Helper method to check if a resource is returning the appropriate
        C{X-FluidDB-Type} header for a given HTTP method.

        @param method: The HTTP method to use. Should be 'GET' or 'HEAD'.
        @param value: The value to test.
        @param expectedTypeString: The expected string that should be returned
            by C{X-FluidDB-Type}.
        """
        facadeClient = FakeFacade()
        session = FakeSession()

        # Tell our FakeFacade to preload some data for a given tag.
        facadeClient.values = {
            'fe2f50c8-997f-4049-a180-9a37543d001d': {
                'tag/test': value}}

        resource = TagInstanceResource(facadeClient, session,
                                       'fe2f50c8-997f-4049-a180-9a37543d001d',
                                       'tag/test')

        request = FakeRequest(method=method)
        yield getattr(resource, 'render_' + method)(request)
        typeValue = request.getResponseHeader(buildHeader('Type'))
        self.assertEqual(expectedTypeString, typeValue)
示例#9
0
    def testContentMD5DoesNotMatch(self):
        """
        Checks that an incoming requests whose payload doesn't match the
        Content-MD5 header and returns a PRECONDITION FAILED (412).
        """

        payload = {"description": "A namespace for tags that I'm using to"
                                  "add to people",
                   "name": "people"}
        content = json.dumps(payload)
        contentLength = len(content)
        request = http.Request(DummyChannel(), False)
        request.method = 'POST'
        request.requestHeaders.setRawHeaders("Content-MD5", ["bad-md5"])
        request.requestHeaders.setRawHeaders("Content-Length",
                                             [str(contentLength)])
        request.requestHeaders.setRawHeaders("Content-Type",
                                             ["application/json"])
        request._fluidDB_reqid = 'xxx'
        request.args = dict()
        request.postpath = []
        request.content = StringIO(content)

        resource = NamespacesResource(FakeFacadeClient(), FakeSession())
        resource.render(request)
        self.assertEqual(request.code, http.PRECONDITION_FAILED)
示例#10
0
    def testRatingForNonexistentObjectAboutParis(self):
        """
        Run GET and HEAD requests against a non-existent object about paris,
        check that both return NOT_FOUND.
        """
        about = 'paris'
        tag = 'ntoll/rating'
        fakeQueryResolver = FakeQueryResolver(about, [], self)
        facadeClient = FakeFacadeClient(fakeQueryResolver=fakeQueryResolver)
        session = FakeSession()
        resource = AboutTagInstanceResource(facadeClient, session, about, tag)

        # Test GET.
        d = defer.Deferred()
        request = FakeRequest('GET', d)
        request.content = StringIO.StringIO()
        resource.render(request)
        yield d
        self.assertEqual(request.status, http.NOT_FOUND)

        # Test HEAD.
        d = defer.Deferred()
        request = FakeRequest('HEAD', d)
        request.content = StringIO.StringIO()
        resource.render(request)
        yield d
        self.assertEqual(request.status, http.NOT_FOUND)
示例#11
0
    def testPUTGETBinaryValueOnObjectAboutAfrica(self):
        """
        PUT a binary value for ntoll/rating onto the object about
        africa. Then do two GET requests:

          - A GET with no Accept header (which means we accept anything)
            and check the result is what we set.
          - Do a GET with an Accept header that prevents FluidDB from
            delivering, and check we get a NOT_ACCEPTABLE status.
        """
        about = 'africa'
        tag = 'ntoll/binary'
        value = '\x00\x01'
        mimetype = 'ntoll/personalbinary'
        objectIdAboutAfrica = util.generateObjectId()
        fakeQueryResolver = FakeQueryResolver(about, [objectIdAboutAfrica],
                                              self)
        fakeTagsClient = FakeTagsClient()
        facadeClient = FakeFacadeClient(fakeTagsClient=fakeTagsClient,
                                        fakeQueryResolver=fakeQueryResolver)
        session = FakeSession()
        resource = AboutTagInstanceResource(facadeClient, session, about, tag)

        # Test PUT.
        payload = value
        headers = {
            'Content-Length': [str(len(payload))],
            'Content-Type': [mimetype],
        }
        d = defer.Deferred()
        request = FakeRequest('PUT', d, headers)
        request.content = StringIO.StringIO(payload)
        resource.render(request)
        yield d
        self.assertEqual(request.status, http.NO_CONTENT)

        # Test GET.
        d = defer.Deferred()
        request = FakeRequest('GET', d)
        request.content = StringIO.StringIO()
        resource.render(request)
        body = yield d
        self.assertEqual(request.status, http.OK)
        self.assertEqual(request.getResponseHeader('Content-Type'), mimetype)
        self.assertEqual(body, value)

        # Test GET when no acceptable Accept header value.
        headers = {'Accept': ['italian/lira, chewing/gum']}
        request = FakeRequest('GET', None, headers)
        request.content = StringIO.StringIO()
        resource.render(request)
        self.assertEqual(request.status, http.NOT_ACCEPTABLE)
示例#12
0
    def testPUTOnNonexistentObjectAboutAfrica(self):
        """
        PUT a value for ntoll/keywords onto the object about africa, even
        though no such object exists.  This should succeed with a CREATED
        status.  We then do a GET to make sure we can retrieve the value.
        BTW, I use a set of strings as a value to increase code coverage of
        about.py

        We want /about to be identical in semantics to /objects/id and so
        this behavior mirrors that of /objects/id/tag/path which does not
        require that the object id exists in order to put a value onto it.
        """
        about = 'africa'
        tag = 'ntoll/keywords'
        value = ['hot', 'dry', 'dusty']
        fakeQueryResolver = FakeQueryResolver(about, [], self)
        fakeTagsClient = FakeTagsClient()
        facadeClient = FakeFacadeClient(fakeTagsClient=fakeTagsClient,
                                        fakeQueryResolver=fakeQueryResolver)
        session = FakeSession()
        resource = AboutTagInstanceResource(facadeClient, session, about, tag)

        # Test PUT.
        payload = json.dumps(value)
        headers = {
            'Content-Length': [str(len(payload))],
            'Content-Type': [contentTypeForPrimitiveJSON],
        }
        d = defer.Deferred()
        request = FakeRequest('PUT', d, headers)
        request.content = StringIO.StringIO(payload)
        resource.render(request)
        self.assertEqual(request.status, http.NO_CONTENT)
        yield d

        # Pull the object id out of the fake tags client and tell the fake
        # query resolver to now give a different answer for the query on
        # africa.
        keys = fakeTagsClient.values[_aboutPath].keys()
        self.assertEqual(len(keys), 1)

        # Test GET.
        d = defer.Deferred()
        request = FakeRequest('GET', d)
        request.content = StringIO.StringIO()
        resource.render(request)
        body = yield d
        self.assertEqual(request.status, http.OK)
        self.assertEqual(request.getResponseHeader('Content-Type'),
                         contentTypeForPrimitiveJSON)
        receivedValue = json.loads(body)
        self.assertEqual(set(value), set(receivedValue))
示例#13
0
 def testAllowedMethodsCheck(self):
     """
     Makes sure _handleOptions throws an exception if allowedMethods is not
     defined in the child class
     """
     request = http.Request(DummyChannel(), False)
     request.method = 'OPTIONS'
     request._fluidDB_reqid = 'xxx'
     request.args = dict()
     request.postpath = []
     request.content = NoContent()
     resource = WSFEResource(FakeFacadeClient(), FakeSession())
     self.assertRaises(RuntimeError, resource._handleOptions, request, None)
示例#14
0
 def testUnseekableContent(self):
     """
     Test that sending a request whose content cannot have seek called
     on it without raising a ValueError gets a 400 Bad Request status,
     with the appropriate C{X-FluidDB-Error-Class} value in the header.
     """
     request = FakeRequest('POST', 'namespaces/fluiddb')
     request.content = NoContent()
     resource = NamespacesResource(None, FakeSession())
     resource.render(request)
     self.assertFalse(request.finished)
     self.assertEqual(request.status, http.BAD_REQUEST)
     self.assertEqual(request.getResponseHeader('X-FluidDB-Error-Class'),
                      error.ContentSeekError.__name__)
示例#15
0
 def testGETNonExistentObjectAboutParis(self):
     """
     Set up a fake query resolver that will give no results for
     fluiddb/about = \"paris\" and then make sure that doing a GET on
     /about/paris results in a NOT_FOUND status.
     """
     about = 'paris'
     fakeQueryResolver = FakeQueryResolver(about, [], self)
     facadeClient = FakeFacadeClient(fakeQueryResolver=fakeQueryResolver)
     session = FakeSession()
     resource = AboutObjectResource(facadeClient, session, about)
     d = defer.Deferred()
     request = FakeRequest('GET', d)
     request.args = {objects.showAboutArg: ['False']}
     request.content = StringIO.StringIO()
     resource.render(request)
     yield d
     self.assertEqual(request.status, http.NOT_FOUND)
示例#16
0
 def testRatingForAboutContainingDoubleQuotes(self):
     """
     Run GET requests against a non-existent object about a string with
     embedded double quotes.  Check that it returns NOT_FOUND.
     """
     about = 'chicken "soup" taste'
     aboutQuoted = r'chicken \"soup\" taste'
     tag = 'ntoll/rating'
     fakeQueryResolver = FakeQueryResolver(aboutQuoted, [], self)
     facadeClient = FakeFacadeClient(fakeQueryResolver=fakeQueryResolver)
     session = FakeSession()
     resource = AboutTagInstanceResource(facadeClient, session, about, tag)
     d = defer.Deferred()
     request = FakeRequest('GET', d)
     request.content = StringIO.StringIO()
     resource.render(request)
     yield d
     self.assertEqual(request.status, http.NOT_FOUND)
示例#17
0
    def testHeaderPresentOn401Error(self):
        """
        Check the WWW-Authenticate header is present, with the expected
        value when we hit a 401 (Unauthorized) error.
        """
        class ExplodingPermissionDeniedFacade(object):
            """
            A fake facade whose C{createNamespace} method always
            raises TPathPermissionDenied.
            """
            def createNamespace(self, *args, **kwargs):
                """
                Make something (unspecified) appear to go wrong with perms
                checking.

                @param args: Positional arguments for the new namespace.
                @param kwargs: Keyword arguments for the new namespace.
                @raise C{TPathPermissionDenied} no matter what.
                """
                raise TPathPermissionDenied()

        payload = {'description': 'A new namespace', 'name': 'people'}
        content = json.dumps(payload)
        contentLength = len(content)
        request = http.Request(DummyChannel(), False)
        request.method = 'POST'
        request.requestHeaders.setRawHeaders('Content-Length',
                                             [str(contentLength)])
        request.requestHeaders.setRawHeaders('Content-Type',
                                             ['application/json'])
        request.requestHeaders.setRawHeaders('Host', ['fluiddb.fluidinfo.com'])
        request._fluidDB_reqid = 'xxx'
        request.args = dict()
        request.postpath = []
        request.content = StringIO(content)
        resource = NamespacesResource(ExplodingPermissionDeniedFacade(),
                                      FakeSession())
        resource.render(request)
        # Check the response code and header content.
        self.assertEqual(request.code, http.UNAUTHORIZED)
        headers = request.responseHeaders
        self.assertTrue(headers.hasHeader('WWW-Authenticate'))
        self.assertEqual('Basic realm="Fluidinfo"',
                         headers.getRawHeaders('WWW-Authenticate')[0])
示例#18
0
 def testPOSTObjectAboutChickenSoup(self):
     """
     Test that a POST to /about/chicken%20soup results in a CREATED
     status and that we get back the id of the object that already
     existed (as will be supplied by the fake query resolver).
     """
     about = 'chicken soup'
     objectId = util.generateObjectId()
     fakeQueryResolver = FakeQueryResolver(about, [objectId], self)
     facadeClient = FakeFacadeClient(fakeQueryResolver=fakeQueryResolver)
     session = FakeSession()
     resource = AboutObjectResource(facadeClient, session, about)
     d = defer.Deferred()
     request = FakeRequest('POST', d)
     request.content = StringIO.StringIO()
     resource.render(request)
     body = yield d
     self.assertEqual(request.status, http.CREATED)
     responseDict = json.loads(body)
     self.assertEqual(responseDict['id'], objectId)
示例#19
0
 def testGETAboutWithDoubleQuotes(self):
     '''
     Test that a GET to /about/chicken%20"soup"%20taste results in an OK
     status and that we get back the id of the object that already
     existed (as will be supplied by the fake query resolver).
     '''
     about = 'chicken "soup" taste'
     aboutQuoted = r'chicken \"soup\" taste'
     objectId = util.generateObjectId()
     fakeQueryResolver = FakeQueryResolver(aboutQuoted, [objectId], self)
     facadeClient = FakeFacadeClient(fakeQueryResolver=fakeQueryResolver)
     session = FakeSession()
     resource = AboutObjectResource(facadeClient, session, about)
     d = defer.Deferred()
     request = FakeRequest('GET', d)
     request.args = {objects.showAboutArg: ['False']}
     request.content = StringIO.StringIO()
     resource.render(request)
     yield d
     self.assertEqual(request.status, http.OK)
示例#20
0
    def testGETListValuesPreserveOrder(self):
        """
        List values get via GET on /objects preserve the same order of the
        original value.
        """
        facadeClient = FakeFacade()
        session = FakeSession()

        # Tell our FakeFacade to preload some data for a given tag.
        facadeClient.values = {
            'fe2f50c8-997f-4049-a180-9a37543d001d': {
                'tag/test': ['x', 'y', 'z', 'a', 'b', 'c']}}

        resource = TagInstanceResource(facadeClient, session,
                                       'fe2f50c8-997f-4049-a180-9a37543d001d',
                                       'tag/test')

        request = FakeRequest(method='GET')
        body = yield resource.deferred_render_GET(request)
        value = json.loads(body)
        self.assertEqual(['x', 'y', 'z', 'a', 'b', 'c'], value)
示例#21
0
    def assertXFluidDBHeaderForType(self, method, value, expectedTypeString):
        """
        L{TagInstanceResource.render_HEAD} should put an X-FluidDB-Type header
        indicating the type of the value that it's returning. This tests
        checks float types.
        """
        facadeClient = SimpleFakeFacade()
        session = FakeSession()
        # Tell our FakeFacade to preload some data for a given tag.
        facadeClient.values = {
            'fe2f50c8-997f-4049-a180-9a37543d001d': {
                'tag/test': value,
                'fluiddb/about': 'about tag'
            }
        }

        resource = AboutTagInstanceResource(facadeClient, session, 'about tag',
                                            'tag/test')

        request = FakeRequest(method, {}, {}, '')
        yield getattr(resource, 'render_' + method)(request)
        typeValue = request.getResponseHeader(buildHeader('Type'))
        self.assertEqual(expectedTypeString, typeValue)
示例#22
0
 def testGETObjectAboutBarcelona(self):
     """
     Test that a GET of /about/barcelona results in an OK status and
     that we get back the id of the object that already existed (as will
     be supplied by the fake query resolver), and that it has no tags on
     it.
     """
     about = 'barcelona'
     objectId = util.generateObjectId()
     fakeQueryResolver = FakeQueryResolver(about, [objectId], self)
     facadeClient = FakeFacadeClient(fakeQueryResolver=fakeQueryResolver)
     session = FakeSession()
     resource = AboutObjectResource(facadeClient, session, about)
     d = defer.Deferred()
     request = FakeRequest('GET', d)
     request.args = {objects.showAboutArg: ['False']}
     request.content = StringIO.StringIO()
     resource.render(request)
     body = yield d
     self.assertEqual(request.status, http.OK)
     responseDict = json.loads(body)
     self.assertEqual(responseDict[objects.tagPathsArg], [])
     self.assertEqual(responseDict['id'], objectId)
示例#23
0
    def testPUTGETNonBinaryWithNoAcceptableType(self):
        """
        PUT a primitive (non-binary) value for ntoll/rating onto the object
        about africa. Then do a GET with an Accept header that prevents
        FluidDB from delivering, and check we get a NOT_ACCEPTABLE status.
        """
        about = 'africa'
        tag = 'ntoll/binary'
        value = 5
        objectIdAboutAfrica = util.generateObjectId()
        fakeQueryResolver = FakeQueryResolver(about, [objectIdAboutAfrica],
                                              self)
        fakeTagsClient = FakeTagsClient()
        facadeClient = FakeFacadeClient(fakeTagsClient=fakeTagsClient,
                                        fakeQueryResolver=fakeQueryResolver)
        session = FakeSession()
        resource = AboutTagInstanceResource(facadeClient, session, about, tag)

        # Test PUT.
        payload = json.dumps(value)
        headers = {
            'Content-Length': [str(len(payload))],
            'Content-Type': [contentTypeForPrimitiveJSON],
        }
        d = defer.Deferred()
        request = FakeRequest('PUT', d, headers)
        request.content = StringIO.StringIO(payload)
        resource.render(request)
        yield d
        self.assertEqual(request.status, http.NO_CONTENT)

        # Test GET when no acceptable Accept header value.
        headers = {'Accept': ['italian/lira, chewing/gum']}
        request = FakeRequest('GET', None, headers)
        request.content = StringIO.StringIO()
        resource.render(request)
        self.assertEqual(request.status, http.NOT_ACCEPTABLE)
示例#24
0
 def testHeaderNotPresentWhenNoError(self):
     """
     Check the WWW-Authenticate header is not present
     when we do not hit an error.
     """
     payload = {'description': 'A new namespace', 'name': 'people'}
     content = json.dumps(payload)
     contentLength = len(content)
     request = http.Request(DummyChannel(), False)
     request.method = 'POST'
     request.requestHeaders.setRawHeaders('Content-Length',
                                          [str(contentLength)])
     request.requestHeaders.setRawHeaders('Content-Type',
                                          ['application/json'])
     request.requestHeaders.setRawHeaders('Host', ['fluiddb.fluidinfo.com'])
     request._fluidDB_reqid = 'xxx'
     request.args = dict()
     request.postpath = []
     request.content = StringIO(content)
     resource = NamespacesResource(FakeFacadeClient(), FakeSession())
     resource.render(request)
     # Check the WWW-Authenticate header is absent.
     headers = request.responseHeaders
     self.assertFalse(headers.hasHeader('WWW-Authenticate'))
示例#25
0
    def testPUTWithNoContentTypeNoPayload(self):
        """
        Check that if we attempt a PUT with no payload and no Content-Type,
        we get an (ok) NO_CONTENT status (this is putting a None as the
        value).
        """
        about = 'africa'
        tag = 'ntoll/binary'
        objectIdAboutAfrica = util.generateObjectId()
        fakeQueryResolver = FakeQueryResolver(about, [objectIdAboutAfrica],
                                              self)
        fakeTagsClient = FakeTagsClient()
        facadeClient = FakeFacadeClient(fakeTagsClient=fakeTagsClient,
                                        fakeQueryResolver=fakeQueryResolver)
        session = FakeSession()
        resource = AboutTagInstanceResource(facadeClient, session, about, tag)

        # Test PUT.
        d = defer.Deferred()
        request = FakeRequest('PUT', d)
        request.content = StringIO.StringIO()
        resource.render(request)
        yield d
        self.assertEqual(request.status, http.NO_CONTENT)
示例#26
0
 def testUsersResource(self):
     resource = UsersResource(FakeFacadeClient(), FakeSession())
     self._checkCORSPreFlightRequest(resource, "POST")
示例#27
0
 def testObjectsResource(self):
     resource = ObjectsResource(FakeFacadeClient(), FakeSession())
     self._checkCORSPreFlightRequest(resource)
示例#28
0
 def testConcreteUserResource(self):
     resource = ConcreteUserResource(FakeFacadeClient(),
                                     FakeSession(),
                                     username='******')
     self._checkCORSPreFlightRequest(resource)
示例#29
0
 def testConcretePermissionResource(self):
     resource = ConcretePermissionResource(FakeFacadeClient(),
                                           FakeSession())
     self._checkCORSPreFlightRequest(resource)
示例#30
0
 def testTagInstanceResource(self):
     resource = TagInstanceResource(FakeFacadeClient(),
                                    FakeSession(),
                                    objectId='1234',
                                    path='bar/baz')
     self._checkCORSPreFlightRequest(resource)