pax_global_header00006660000000000000000000000064135776502760014534gustar00rootroot0000000000000052 comment=d7e974896fd19f982dfef5dc57bbd5bedea38c33 sparqlwrapper-1.8.5/000077500000000000000000000000001357765027600144525ustar00rootroot00000000000000sparqlwrapper-1.8.5/.gitignore000066400000000000000000000001341357765027600164400ustar00rootroot00000000000000*~ *.pyc SPARQLWrapper.egg-info build dist doc .idea *.iml .project .pydevproject .settings/sparqlwrapper-1.8.5/.travis.yml000066400000000000000000000012441357765027600165640ustar00rootroot00000000000000# http://travis-ci.org/RDFLib/sparqlwrapper branches: except: - gh-pages sudo: false language: python python: - 2.7 - 3.4 - 3.5 - 3.6 - pypy # Enable 3.7 and 3.8-dev without globally enabling sudo and dist: xenial for other build jobs matrix: include: - python: 3.7 dist: xenial sudo: true - python: 3.8-dev env: ENV=py38-dev dist: xenial sudo: true allow_failures: - env: ENV=py38-dev - python: 'pypy' before_install: - pip install --upgrade pip setuptools install: - python setup.py sdist && pip install ./dist/* before_script: - pip install rdflib-jsonld script: ./tests.sh sparqlwrapper-1.8.5/AUTHORS.md000066400000000000000000000050331357765027600161220ustar00rootroot00000000000000# Authors * Ivan Herman ([@iherman](http://github.com/iherman)) * Sergio Fernández ([@wikier](http://github.com/wikier)) * Carlos Tejo ([@dayures](http://github.com/dayures)) * Alexey Zakhlestin ([@indeyets](http://github.com/indeyets)) # Contributors * Obey Arthur Liu ([@ArthurLiu](http://github.com/ArthurLiu)): different patches * Christopher Lenz ([@cmlenz](http://github.com/cmlenz)): feature to allow developers to choose the json module * Pēteris Caune ([@cuu508](http://github.com/cuu508)): great feedback and patches * Bogdan Benea ([bugdone@users.sourceforge.net](mailto:bugdone@users.sourceforge.net)), patch for the query regular expresion * William Waites ([@wwaites](http://github.com/wwaites)): patches for RDFLib3 * Christoph Burgmer ([@cburgmer](http://github.com/cburgmer)): patches for RDFLib3 * Thomas Kluyver ([@takluyver](http://github.com/takluyver)): patches for Python 3.x * Diego Berrueta ([@berrueta](http://github.com/berrueta)): new function for printing results as table * Olivier Berger ([@olberger](http://github.com/olberger)): patch regarding raw response for unknown formats * Benjamin Cogrel ([@bcogrel](http://github.com/bcogrel)): standard query types * Urs Holzer ([@uholzer](http://github.com/uholzer)): features, patches and testing * Alf Lervåg ([@alf](http://github.com/alf)): setup patch * Nolan Nichols ([@nicholsn](http://github.com/nicholsn)): http disgest auth support * Kevin Turner ([@keturn](https://github.com/keturn)): `SmartWrapper.Value.__repr__()` implementation * Marcelo Jorge Vieira ([@marcelometal](https://github.com/marcelometal)): typos * Trevor Andersen ([@trevorandersen](https://github.com/trevorandersen): patches for Python 3.x * Carlos Martinez-Ortiz ([@cmartinez](https://github.com/cmartinez): improves support for return format HTTP parameter * Christian Amsüss ([@chrysn](https://github.com/chrysn)): dependecy fixes * Chris Lamb ([@lamby](https://github.com/lamby)): typo * Hugo van Kemenade ([@hugovk](https://github.com/hugovk)): update classifiers (Python 3.6) * Edward Betts ([@EdwardBetts](https://github.com/EdwardBetts)): Correct spelling mistakes * Carlos Martínez ([@c-martinez](https://github.com/c-martinez)): Mainly support for CSV and TSV results in SPARQL SELECT queries * Dan Michael O. Heggø ([@danmichaelo](https://github.com/danmichaelo)): update README with SPARQLWrapper2 example * Sam Clements ([@borntyping](https://github.com/borntyping)): Provide hints about setting properly the timeout * Marc Feger ([@MaFeg100](https://github.com/MaFeg100)): Improve/tests for development sparqlwrapper-1.8.5/ChangeLog.txt000066400000000000000000000140621357765027600170450ustar00rootroot00000000000000SPARQLWrapper's changelog ========================= 2019-12-22 1.8.5 ----------------- - Improve/tests for development (#131) - Changed. Be more strict on Accept Turtle header (#137) - Migrated documentation from epydoc to sphinx and readthedocs 2019-04-18 1.8.4 ----------------- - Added example - hotfix: Added custom_fixers folder in MANIFEST, in order to be used in python3 (#129) 2019-04-17 1.8.3 ----------------- - Include ChangeLog.txt in the distribution - Removed import of SPARQLWrapper in setup.py (fixed #113 and closed #115) - Added support for querying RDF/XML in a CONSTRUCT query type - Updated the procedure for determining the query type (#120) - Do not send format parameter for the results ([format, output, results]) when the query is a SPARQL Update query - Added test for new agrovoc SPARQL endpoint (using Fuseki2) - Added test for 4store SPARQL endpoint (used by agroportal) - Added/Updated tests - Added examples - Updated doc - Fixed code generated for python3 using 2to3, adding a custom fixer (#109) 2018-05-26 1.8.2 ----------------- - Fixed bug (#100) - Updated doc - Added Unauthorized exception in SPARQLWrapperExceptions - Added support for custom HTTP headers (#52) - Changed timeout setting (#106) 2018-02-25 1.8.1 ----------------- - Update classifiers (Python 3.6) - Added some documentation about the parameter to indicate the output format - Fixed typo in width calculation - Added support for CSV, TSV (PR #98) - Added support for Only HTTP Content Negotiation (#82) 2016-12-07 1.8.0 ----------------- - Updated return formats for not content negotiation situations - Included license in the MANIFEST (issue #76) - Added explicit support for RDF/XML as allowed format (issue #75) - Added proper shebang (issue #78) - Moved keepalive as optional dependency (issue #79) - Fixed hash check on prefixes (issue #77) - Fixed epydoc warnings (issue #41) 2015-12-18 1.7.6 ----------------- - Removed wrong response encoding (issue #70) - Authorization header bug when using Python 3 (issue #71) 2015-11-19 1.7.5 ----------------- - Removed pip dependency on setup (issue #69) 2015-11-05 1.7.4 ----------------- - Fixed packaging (issue #66) 2015-11-05 1.7.3 ----------------- - Finally fixed the keepalive issue in all Pyhon versions (issue #65) - Removed old JSON layer in favor of the native json module 2015-11-03 1.7.2 ----------------- - Moved to the new keepalive package (issues #53 and #61) 2015-10-29 1.7.1 ----------------- - Fixed build in Python 3.x (issue #57) 2015-10-29 1.7.0 ----------------- - Added support to HTTP Digest Auth Support (issue #45) - Improved print_results showing language tag (xml:lang) and datatype - Updated to RDFLib 4.x 2014-08-26 1.6.4 ----------------- - Fixed unicode problems on setup (issue #42) 2014-08-26 1.6.3 ----------------- - Fixed unicode problems with urllib in Python 3 (issue #35) - Restored SPARQLWrapper2 class (issue #36) - Enhanced warning for missing rdflib-jsonld (issue #38) - Fixed build system (issue #39) 2014-07-24 1.6.2 ----------------- - Fixed query type detection with comments (issue #32) 2014-07-21 1.6.1 ----------------- - Added missing query types (issue #17) - Added a new method to the API to select the request method to be fully SPARQL 1.1 Protocol compliant (issue #28) - Improved the test suite coverage, including support to run the tests under Python 3.x (issues #20, #24 and #31) 2014-05-09 1.6.0 ----------------- - Returning raw response in case of unknown content type returned - Fixed some issues with the last version of the SPARQL 1.1 Update Protocol - setQuery() doesn't imply resetQuery() anymore - Deprecated addCustomParameter(), addParameter() and clearParameter() come to provide all required functionality - SPARQLWrapper, QueryResult, Value, Bindings (and classes inherited from them) are new-style classes now - POST queries are accompanied by full set of parameters now - Added rudimentary support for JSON-LD - Added proper unit tests without dependencies of external endpoints - Fixed Python 3 compatibility issues in SmartWrapper module 2012-08-28 1.5.2 ----------------- - Implemented update operation according the latest SPARQL 1.1 Protocol drafts (i.e., switching to 'update' parameter) 2012-07-10 1.5.1 ----------------- - Added the possibility to use two different endpoints for reading and writing operations - New print_results() function for users testing 2012-02-01 1.5.0 ----------------- - Update handling 500's coming from SPARQL endpoint (feature request #3198363) - Added Python 3.x support (feature request 3022722) - Warning when returned format would be different than the requested one 2011-01-28 1.4.2 ----------------- - Updated for working with RDFLib3 too (feature request #3117442) - fixed bug with prefixes' regex (#2320024) 2010-01-11 1.4.1 ----------------- - Supporting keep-alive in SPARQLWrapper if urlgrabber is available (ticket #2929881) - fixed bugs (#2949834) 2009-12-14 1.4.0 ----------------- - Added some support for SPARUL - Improved HTTP related code - Many other minor bugs fixed 2009-09-23 1.3.2 ----------------- - Remove pyxml dependency. Instead, use xml.dom.minidom - Updated setup installation (added rdflib dependency) - Updated example.py (added XML, N3 and RDF examples) 2009-09-11 1.3.1 ----------------- - Remove simplejson dependency for python => 2.6 version - Added feature to choose the json module to use 2009-05-06 1.3.0 ----------------- - Added a new method to add custom parameters (deprecated old way to do it) 2009-04-27 1.2.1 ----------------- - Updated setup installation - Patched to work with JSON in Python>=2.6 2008-07-10 1.2.0 ----------------- - Allowed non-standard extensions (such as SPARUL). - Exceptions fixed. - Added another example. 2008-03-24 1.1.0 ----------------- - Renamed package name to SPARQLWrapper. - Added a basic catalog of exceptions. 2008-03-07 1.0.1 ----------------- - Fixed some cosmetic things. 2008-02-14 1.0.0 ----------------- - First stable release. - Main functionality stabilized. - Project moved to SourceForge. 2007-07-06 0.2.0 ----------------- - First public release of the library. sparqlwrapper-1.8.5/LICENSE.txt000066400000000000000000000041261357765027600163000ustar00rootroot00000000000000SPARQL Python Wrapper is released under the W3C SOFTWARE NOTICE AND LICENSE. This work (and included software, documentation such as READMEs, or other related items) is being provided by the copyright holders under the following license. By obtaining, using and/or copying this work, you (the licensee) agree that you have read, understood, and will comply with the following terms and conditions. Permission to copy, modify, and distribute this software and its documentation, with or without modification, for any purpose and without fee or royalty is hereby granted, provided that you include the following on ALL copies of the software and documentation or portions thereof, including modifications: 1. The full text of this NOTICE in a location viewable to users of the redistributed or derivative work. 2. Any pre-existing intellectual property disclaimers, notices, or terms and conditions. If none exist, the W3C Software Short Notice should be included (hypertext is preferred, text is permitted) within the body of any redistributed or derivative code. 3. Notice of any changes or modifications to the files, including the date changes were made. (We recommend you provide URIs to the location from which the code is derived.) THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS. COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR DOCUMENTATION. The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to the software without specific, written prior permission. Title to copyright in this software and any associated documentation will at all times remain with copyright holders. See also http://www.w3.org/Consortium/Legal/copyright-software for further details sparqlwrapper-1.8.5/MANAGEMENT.md000066400000000000000000000025041357765027600164110ustar00rootroot00000000000000# Management documentation The project keeps a very low-profile on managing, so we try to keep it simple. ## Contributions Every contributor (patchs, pull requests, new features, etc) gets part of ownership by be mentioned as contributor to the project (`AUTHORS.md`). ## Release ### Software The release process is quite simple, just few things have to be done: First, do not forget to update the changelog (`ChangeLog.txt` file). That information could be added later to the release at github. Then you have to [create a release](https://github.com/blog/1547-release-your-software) by tagging the master branch: git tag x.y.z git push --tags And then upload the release to pypi: python setup.py register sdist --formats=gztar,zip bdist_egg upload Please, don't forget to increment to the next module (`SPARQLWrapper/__init__.py` file). ### Documentation In order to provide online documentation, some steps need to be accomplished: 1. First, generate the documentation using [sphinx](http://www.sphinx-doc.org/) using the makefile $ cd docs $ make clean && make html 2. And then upload the documentation generated (`doc` folder) to GitHub Pages (`gh-pages` branch). 3. After that, the online version of the documentation would be available on [GitHub Pages](http://rdflib.github.io/sparqlwrapper/resources/doc). sparqlwrapper-1.8.5/MANIFEST.in000066400000000000000000000002621357765027600162100ustar00rootroot00000000000000include *.md exclude Makefile include test/*.py include scripts/*.py include requirements.txt include LICENSE.txt include ChangeLog.txt graft custom_fixers graft docs/build/html sparqlwrapper-1.8.5/Makefile000066400000000000000000000004301357765027600161070ustar00rootroot00000000000000# SPARQLWrapper Makefile NAME=SPARQLWrapper VERSION=`python -c "import SPARQLWrapper,sys;sys.stdout.write(SPARQLWrapper.__version__)";` DESTDIR = DOCDIR=docs doc: clean $(MAKE) -C ${DOCDIR} html clean: $(MAKE) -C ${DOCDIR} clean rm -rf build find . -name "*.pyc" -delete sparqlwrapper-1.8.5/README.rst000066400000000000000000000322621357765027600161460ustar00rootroot00000000000000======================================= SPARQL Endpoint interface to Python ======================================= |Build Status| |PyPi version| About ===== **SPARQLWrapper** is a simple Python wrapper around a `SPARQL `_ service to remotelly execute your queries. It helps in creating the query invokation and, possibly, convert the result into a more manageable format. Installation & Distribution =========================== You can install SPARQLWrapper from PyPi:: $ pip install sparqlwrapper You can install SPARQLWrapper from GitHub:: $ pip install git+https://github.com/rdflib/sparqlwrapper#egg=sparqlwrapper You can install SPARQLWrapper from Debian:: $ sudo apt-get install python-sparqlwrapper .. note:: Be aware that there could be a gap between the latest version of SPARQLWrapper and the version available as Debian package. Also, the source code of the package can be downloaded in ``.zip`` and ``.tar.gz`` formats from `GitHub SPARQLWrapper releases `_. Documentation is included in the distribution. How to use ========== First steps ----------- The simplest usage of this module looks as follows (using the default, ie, `XML return format `_, and special URI for the SPARQL Service):: from SPARQLWrapper import SPARQLWrapper queryString = "SELECT * WHERE { ?s ?p ?o. }" sparql = SPARQLWrapper("http://example.org/sparql") sparql.setQuery(queryString) try : ret = sparql.query() # ret is a stream with the results in XML, see except : deal_with_the_exception() If ``SPARQLWrapper("http://example.org/sparql",returnFormat=SPARQLWrapper.JSON)`` was used, the result would be in `JSON format `_ instead of XML. SELECT example -------------- .. code:: python from SPARQLWrapper import SPARQLWrapper, JSON sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX rdfs: SELECT ?label WHERE { rdfs:label ?label } """) sparql.setReturnFormat(JSON) results = sparql.query().convert() for result in results["results"]["bindings"]: print(result["label"]["value"]) print('---------------------------') for result in results["results"]["bindings"]: print('%s: %s' % (result["label"]["xml:lang"], result["label"]["value"])) ASK example ----------- .. code:: python from SPARQLWrapper import SPARQLWrapper, XML sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" ASK WHERE { rdfs:label "Asturias"@es } """) sparql.setReturnFormat(XML) results = sparql.query().convert() print(results.toxml()) CONSTRUCT example ----------------- .. code:: python from SPARQLWrapper import SPARQLWrapper, RDFXML from rdflib import Graph sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX dbo: PREFIX schema: CONSTRUCT { ?lang a schema:Language ; schema:alternateName ?iso6391Code . } WHERE { ?lang a dbo:Language ; dbo:iso6391Code ?iso6391Code . FILTER (STRLEN(?iso6391Code)=2) # to filter out non-valid values } """) sparql.setReturnFormat(RDFXML) results = sparql.query().convert() print(results.serialize(format='xml')) DESCRIBE example ---------------- .. code:: python from SPARQLWrapper import SPARQLWrapper, N3 from rdflib import Graph sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" DESCRIBE """) sparql.setReturnFormat(N3) results = sparql.query().convert() g = Graph() g.parse(data=results, format="n3") print(g.serialize(format='n3')) SPARQL UPDATE example --------------------- .. code:: python from SPARQLWrapper import SPARQLWrapper, POST, DIGEST sparql = SPARQLWrapper("https://example.org/sparql-auth") sparql.setHTTPAuth(DIGEST) sparql.setCredentials("login", "password") sparql.setMethod(POST) sparql.setQuery(""" WITH DELETE { rdfs:label "Asturies"@ast } """) results = sparql.query() print results.response.read() SPARQLWrapper2 example ---------------------- There is also a ``SPARQLWrapper2`` class that works with JSON SELECT results only and wraps the results to make processing of average queries a bit simpler. .. code:: python from SPARQLWrapper import SPARQLWrapper2 sparql = SPARQLWrapper2("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX rdfs: SELECT ?label WHERE { rdfs:label ?label } """) for result in sparql.query().bindings: print('%s: %s' % (result["label"].lang, result["label"].value)) Return formats ------------------------ The expected return formats differs from the query type (``SELECT``, ``ASK``, ``CONSTRUCT``, ``DESCRIBE``...). .. note:: From the `SPARQL specification `_, *The response body of a successful query operation with a 2XX response is either:* * ``SELECT`` and ``ASK``: a SPARQL Results Document in XML, JSON, or CSV/TSV format. * ``DESCRIBE`` and ``CONSTRUCT``: an RDF graph serialized, for example, in the RDF/XML syntax, or an equivalent RDF graph serialization. The package, though it does not contain a full SPARQL parser, makes an attempt to determine the query type when the query is set. This should work in most of the cases (but there is a possibility to set this manually, in case something goes wrong). Automatic conversion of the results ----------------------------------- To make processing somewhat easier, the package can do some conversions automatically from the return result. These are: * for XML, the `xml.dom.minidom `_ is used to convert the result stream into a ``Python representation of a DOM tree``. * for JSON, the `json `_ package to generate a ``Python dictionary``. Until version 1.3.1, the `simplejson `_ package was used. * for CSV or TSV, a simple ``string``. * For RDF/XML and JSON-LD, the `RDFLib `_ package is used to convert the result into a ``Graph`` instance. * For RDF Turtle/N3, a simple ``string``. There are two ways to generate this conversion: * use ``ret.convert()`` in the return result from ``sparql.query()`` in the code above * use ``sparql.queryAndConvert()`` to get the converted result right away if the intermediate stream is not used For example, in the code below:: try : sparql.setReturnFormat(SPARQLWrapper.JSON) ret = sparql.query() dict = ret.convert() except: deal_with_the_exception() the value of ``dict`` is a Python dictionary of the query result, based on the `SPARQL Query Results JSON Format `_. Partial interpretation of the results ------------------------------------- A further help is to offer an extra, partial interpretation of the results, again to cover most of the practical use cases. Based on the `SPARQL Query Results JSON Format `_, the :class:`SPARQLWrapper.SmartWrapper.Bindings` class can perform some simple steps in decoding the JSON return results. If :class:`SPARQLWrapper.SmartWrapper.SPARQLWrapper2` is used instead of :class:`SPARQLWrapper.Wrapper.SPARQLWrapper`, this result format is generated. Note that this relies on a JSON format only, ie, it has to be checked whether the SPARQL service can return JSON or not. Here is a simple code that makes use of this feature:: from SPARQLWrapper import SPARQLWrapper2 queryString = "SELECT ?subj ?prop WHERE { ?subj ?prop ?o. }" sparql = SPARQLWrapper2("http://example.org/sparql") sparql.setQuery(queryString) try : ret = sparql.query() print ret.variables # this is an array consisting of "subj" and "prop" for binding in ret.bindings : # each binding is a dictionary. Let us just print the results print "%s: %s (of type %s)" % ("s",binding[u"subj"].value,binding[u"subj"].type) print "%s: %s (of type %s)" % ("p",binding[u"prop"].value,binding[u"prop"].type) except: deal_with_the_exception() To make this type of code even easier to realize, the ``[]`` and ``in`` operators are also implemented on the result of :class:`SPARQLWrapper.SmartWrapper.Bindings`. This can be used to check and find a particular binding (ie, particular row in the return value). This features becomes particularly useful when the ``OPTIONAL`` feature of SPARQL is used. For example:: from SPARQLWrapper import SPARQLWrapper2 queryString = "SELECT ?subj ?o ?opt WHERE { ?subj ?o. OPTIONAL { ?subj ?opt }}" sparql = SPARQLWrapper2("http://example.org/sparql") sparql.setQuery(queryString) try : ret = sparql.query() print ret.variables # this is an array consisting of "subj", "o", "opt" if (u"subj",u"prop",u"opt") in ret : # there is at least one binding covering the optional "opt", too bindings = ret[u"subj",u"o",u"opt"] # bindings is an array of dictionaries with the full bindings for b in bindings : subj = b[u"subj"].value o = b[u"o"].value opt = b[u"opt"].value # do something nice with subj, o, and opt # another way of accessing to values for a single variable: # take all the bindings of the "subj" subjbind = ret.getValues(u"subj") # an array of Value instances ... except: deal_with_the_exception() GET or POST ----------- By default, all SPARQL services are invoked using HTTP **GET** verb. However, **POST** might be useful if the size of the query extends a reasonable size; this can be set in the query instance. Note that some combination may not work yet with all SPARQL processors (e.g., there are implementations where **POST + JSON return** does not work). Hopefully, this problem will eventually disappear. Development =========== Requirements ------------ The `RDFLib `_ package is used for RDF parsing. This package is imported in a lazy fashion, ie, only when needed. Ie, if the user never intends to use the RDF format, the RDFLib package is not imported and the user does not have to install it. Source code ----------- The source distribution contains: - ``SPARQLWrapper``: the Python package. You should copy the directory somewhere into your PYTHONPATH. Alternatively, you can also run the distutils scripts: ``python setup.py install`` - ``test``: some unit and integrations tests. In order to run the tests some packages have to be installed before. So please install the packages listed in requirements.development.txt: ``pip install -r requirements.development.txt`` - ``scripts``: some scripts to run the package against some SPARQL endpoints. - ``docs``: the documentation. - ``custom_fixers``: 2to3 custom_fixer in order to fix an issue with urllib2._opener. Community ========= Community support is available through the developer's discussion group `rdflib-dev `_. The `archives `_. from the old mailing list are still available. Issues ====== Please, `report any issue to github `_. Documentation ============= The `SPARQLWrapper documentation is available online `_. Other interesting documents are the latest `SPARQL 1.1 Specification (W3C Recommendation 21 March 2013) `_ and the initial `SPARQL Specification (W3C Recommendation 15 January 2008) `_. License ======= The SPARQLWrapper package is licensed under `W3C license`_. .. _W3C license: https://www.w3.org/Consortium/Legal/2015/copyright-software-and-document Acknowledgement =============== The package was greatly inspired by `Lee Feigenbaum's similar package for Javascript `_. Developers involved: * Ivan Herman * Sergio Fernández * Carlos Tejo Alonso * Alexey Zakhlestin Organizations involved: * `World Wide Web Consortium `_ * `Salzburg Research `_ * `Foundation CTIC `_ .. |Build Status| image:: https://secure.travis-ci.org/RDFLib/sparqlwrapper.svg?branch=master :target: https://travis-ci.org/RDFLib/sparqlwrapper .. |PyPi version| image:: https://badge.fury.io/py/SPARQLWrapper.svg :target: https://pypi.python.org/pypi/SPARQLWrapper sparqlwrapper-1.8.5/SPARQLWrapper/000077500000000000000000000000001357765027600170155ustar00rootroot00000000000000sparqlwrapper-1.8.5/SPARQLWrapper/KeyCaseInsensitiveDict.py000066400000000000000000000023331357765027600237410ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ A simple implementation of a key case-insensitive dictionary. .. Developers involved: * Ivan Herman * Sergio Fernández * Carlos Tejo Alonso * Alexey Zakhlestin Organizations involved: * `World Wide Web Consortium `_ * `Foundation CTIC `_ :license: `W3C® Software notice and license `_ """ class KeyCaseInsensitiveDict(dict): """ A simple implementation of a key case-insensitive dictionary """ def __init__(self, d={}): """ :param dict d: The source dictionary. """ for k, v in d.items(): self[k] = v def __setitem__(self, key, value): if hasattr(key, "lower"): key = key.lower() dict.__setitem__(self, key, value) def __getitem__(self, key): if hasattr(key, "lower"): key = key.lower() return dict.__getitem__(self, key) def __delitem__(self, key): if hasattr(key, "lower"): key = key.lower() dict.__delitem__(self, key) sparqlwrapper-1.8.5/SPARQLWrapper/SPARQLExceptions.py000066400000000000000000000046071357765027600224420ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ SPARQL Wrapper exceptions .. Developers involved: * Ivan Herman * Sergio Fernández * Carlos Tejo Alonso * Alexey Zakhlestin Organizations involved: * `World Wide Web Consortium `_ * `Foundation CTIC `_ :license: `W3C® Software notice and license `_ """ class SPARQLWrapperException(Exception): """ Base class for SPARQL Wrapper exceptions """ msg = "an exception has occurred" def __init__(self, response=None): """ :param string response: The server response """ if response: formatted_msg = "%s: %s. \n\nResponse:\n%s" % (self.__class__.__name__, self.msg, response) else: formatted_msg = "%s: %s." % (self.__class__.__name__, self.msg) super(SPARQLWrapperException, self).__init__(formatted_msg) class EndPointInternalError(SPARQLWrapperException): """ Exception type for Internal Server Error responses. Usually HTTP response status code ``500``. """ msg = "endpoint returned code 500 and response" class QueryBadFormed(SPARQLWrapperException): """ Query Bad Formed exception. Usually HTTP response status code ``400``. """ msg = "a bad request has been sent to the endpoint, probably the sparql query is bad formed" class EndPointNotFound(SPARQLWrapperException): """ End Point Not Found exception. Usually HTTP response status code ``404``. """ msg = "it was impossible to connect with the endpoint in that address, check if it is correct" class Unauthorized(SPARQLWrapperException): """ Access is denied due to invalid credentials (unauthorized). Usually HTTP response status code ``401``. .. versionadded:: 1.8.2 """ msg = "access is denied due to invalid credentials (unauthorized). Check the credentials" class URITooLong(SPARQLWrapperException): """ The URI requested by the client is longer than the server is willing to interpret. Usually HTTP response status code ``414``. .. versionadded:: 1.8.3 """ msg = "the URI requested by the client is longer than the server is willing to interpret. Check if the request was sent using GET method instead of POST method." sparqlwrapper-1.8.5/SPARQLWrapper/SmartWrapper.py000066400000000000000000000326431357765027600220260ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ .. Developers involved: * Ivan Herman * Sergio Fernández * Carlos Tejo Alonso * Alexey Zakhlestin Organizations involved: * `World Wide Web Consortium `_ * `Foundation CTIC `_ :license: `W3C® Software notice and license `_ :requires: `RDFLib `_ package. """ import urllib2 from types import * import SPARQLWrapper from SPARQLWrapper.Wrapper import JSON, SELECT ###################################################################################### class Value(object): """ Class encapsulating a single binding for a variable. :ivar variable: The original variable, stored for an easier reference. :vartype variable: string :ivar value: Value of the binding. :vartype value: string :ivar type: Type of the binding. One of :attr:`Value.URI`, :attr:`Value.Literal`, :attr:`Value.TypedLiteral`, or :attr:`Value.BNODE`. :vartype type: string :ivar lang: Language tag of the binding, or ``None`` if not set. :vartype lang: string :ivar datatype: Datatype of the binding, or ``None`` if not set. It is an URI. :vartype datatype: string """ URI = "uri" """the string denoting a URI variable.""" Literal = "literal" """the string denoting a Literal variable.""" TypedLiteral = "typed-literal" """the string denoting a typed literal variable.""" BNODE = "bnode" """the string denoting a blank node variable.""" def __init__(self, variable, binding): """ :param variable: the variable for that binding. Stored for an easier reference. :type variable: string :param binding: the binding dictionary part of the return result for a specific binding. :type binding: dict """ self.variable = variable self.value = binding['value'] self.type = binding['type'] self.lang = None self.datatype = None try: self.lang = binding['xml:lang'] except: # no lang is set pass try: self.datatype = binding['datatype'] except: pass def __repr__(self): cls = self.__class__.__name__ return "%s(%s:%r)" % (cls, self.type, self.value) ###################################################################################### class Bindings(object): """ Class encapsulating one query result, based on the JSON return format. It decodes the return values to make it a bit more usable for a standard usage. The class consumes the return value and instantiates a number of attributes that can be consulted directly. See the list of variables. The `Serializing SPARQL Query Results in JSON `_ explains the details of the JSON return structures. Very succinctly: the return data has "bindings", which means a list of dictionaries. Each dictionary is a possible binding of the SELECT variables to :class:`Value` instances. This structure is made a bit more usable by this class. :ivar fullResult: The original dictionary of the results, stored for an easier reference. :vartype fullResult: dict :ivar head: Header part of the return, see the JSON return format document for details. :vartype head: dict :ivar variables: List of unbounds (variables) of the original query. It is a list of strings. ``None`` in the case of an ASK query. :vartype variables: list :ivar bindings: The final bindings: list of dictionaries, mapping variables to :class:`Value` instances. \ If unbound, then no value is set in the dictionary; that can be easily checked with \ ``var in res.bindings[..]``, for example. :vartype bindings: list :ivar askResult: by default, set to **False**; in case of an ASK query, the result of the query. :vartype askResult: bool """ def __init__(self, retval): """ :param retval: the query result. :type retval: :class:`QueryResult` """ self.fullResult = retval._convertJSON() self.head = self.fullResult['head'] self.variables = None try: self.variables = self.fullResult['head']['vars'] except: pass self.bindings = [] try: for b in self.fullResult['results']['bindings']: # this is a single binding. It is a dictionary per variable; each value is a dictionary again that has to be # converted into a Value instance newBind = {} for key in self.variables: if key in b: # there is a real binding for this key newBind[key] = Value(key, b[key]) self.bindings.append(newBind) except: pass self.askResult = False try: self.askResult = self.fullResult["boolean"] except: pass def getValues(self, key): """A shorthand for the retrieval of all bindings for a single key. It is equivalent to ``[b[key] for b in self[key]]`` :param key: possible variable name. :type key: string :return: list of :class:`Value` instances. :rtype: list """ try: return [b[key] for b in self[key]] except: return [] def __contains__(self, key): """Emulation of the "``key in obj``" operator. Key can be a string for a variable or an array/tuple of strings. If ``key`` is a variable, the return value is ``True`` if there is at least one binding where ``key`` is bound. If ``key`` is an array or tuple, the return value is ``True`` if there is at least one binding where *all* variables in ``key`` are bound. :param key: possible variable, or array/tuple of variables :return: whether there is a binding of the variable in the return :rtype: Boolean """ if len(self.bindings) == 0: return False if type(key) is list or type(key) is tuple: # check first whether they are all really variables if False in [k in self.variables for k in key]: return False for b in self.bindings: # try to find a binding where all key elements are present if False in [k in b for k in key]: # this is not a binding for the key combination, move on... continue else: # yep, this one is good! return True return False else: if key not in self.variables: return False for b in self.bindings: if key in b: return True return False def __getitem__(self, key): """Emulation of the ``obj[key]`` operator. Slice notation is also available. The goal is to choose the right bindings among the available ones. The return values are always arrays of bindings, ie, arrays of dictionaries mapping variable keys to :class:`Value` instances. The different value settings mean the followings: - ``obj[key]`` returns the bindings where ``key`` has a valid value - ``obj[key1,key2,...]`` returns the bindings where *all* ``key1,key2,...`` have valid values - ``obj[(key1,key2,...):(nkey1,nkey2,...)]`` returns the bindings where all ``key1,key2,...`` have valid values and *none* of the ``nkey1,nkey2,...`` have valid values - ``obj[:(nkey1,nkey2,...)]`` returns the bindings where *none* of the ``nkey1,nkey2,...`` have valid values In all cases complete bindings are returned, ie, the values for other variables, not present among the keys in the call, may or may not be present depending on the query results. :param key: possible variable or array/tuple of keys with possible slice notation :return: list of bindings :rtype: array of variable -> :class:`Value` dictionaries """ def _checkKeys(keys): if len(keys) == 0: return False for k in keys: if not isinstance(k, basestring) or not k in self.variables: return False return True def _nonSliceCase(key): if isinstance(key, basestring) and key != "" and key in self.variables: # unicode or string: return [key] elif type(key) is list or type(key) is tuple: if _checkKeys(key): return key return False # The arguments should be reduced to arrays of variables, ie, unicode strings yes_keys = [] no_keys = [] if type(key) is slice: # Note: None for start or stop is all right if key.start: yes_keys = _nonSliceCase(key.start) if not yes_keys: raise TypeError if key.stop: no_keys = _nonSliceCase(key.stop) if not no_keys: raise TypeError else: yes_keys = _nonSliceCase(key) # got it right, now get the right binding line with the constraints retval = [] for b in self.bindings: # first check whether the 'yes' part is all there: if False in [k in b for k in yes_keys]: continue if True in [k in b for k in no_keys]: continue # if we got that far, we shouild be all right! retval.append(b) # if retval is of zero length, no hit; an exception should be raised to stay within the python style if len(retval) == 0: raise IndexError return retval def convert(self): """This is just a convenience method, returns ``self``. Although :class:`SPARQLWrapper2.Bindings` is not a subclass of :class:`SPARQLWrapper.QueryResult`, it is returned as a result by :func:`SPARQLWrapper2.query`, just like :class:`QueryResult` is returned by :func:`SPARQLWrapper.query()`. Consequently, having an empty :func:`convert` method to imitate :class:`QueryResult's convert() method` may avoid unnecessary problems. """ return self ############################################################################################################## class SPARQLWrapper2(SPARQLWrapper.SPARQLWrapper): """Subclass of :class:`~SPARQLWrapper.Wrapper.SPARQLWrapper` that works with a JSON SELECT return result only. The query result is automatically set to a :class:`Bindings` instance. Makes the average query processing a bit simpler...""" def __init__(self, baseURI, defaultGraph=None): """ Class encapsulating a full SPARQL call. In contrast to the :class:`~SPARQLWrapper.Wrapper.SPARQLWrapper` superclass, the return format cannot be set (it is defaulted to :attr:`~SPARQLWrapper.Wrapper.SPARQLWrapper.JSON`). :param baseURI: string of the SPARQL endpoint's URI. :type baseURI: string :param defaultGraph: URI for the default graph. Default is ``None``, can be set via an explicit call, too. :type defaultGraph: string """ super(SPARQLWrapper2, self).__init__(baseURI, returnFormat=JSON, defaultGraph=defaultGraph) def setReturnFormat(self, format): """ Set the return format (:meth:`overriding the inherited method `). .. warning:: This method does nothing; this class instance should work with JSON only. The method is defined \ just to avoid possible errors by erroneously setting the return format. \ When using this class, the user can safely ignore this call. :param format: return format :type format: string """ pass def query(self): """ Execute the query and do an automatic conversion. Exceptions can be raised if either the URI is wrong or the HTTP sends back an error. The usual urllib2 exceptions are raised, which cover possible SPARQL errors, too. If the query type is *not* SELECT, the method falls back to the :meth:`corresponding method in the superclass`. :return: query result :rtype: :class:`Bindings` instance """ res = super(SPARQLWrapper2, self).query() if self.queryType == SELECT: return Bindings(res) else: return res def queryAndConvert(self): """This is here to override the inherited method; it is equivalent to :class:`query`. If the query type is *not* SELECT, the method falls back to the :meth:`corresponding method in the superclass`. :return: the converted query result. """ if self.queryType == SELECT: return self.query() else: return super(SPARQLWrapper2, self).queryAndConvert() sparqlwrapper-1.8.5/SPARQLWrapper/Wrapper.py000066400000000000000000002167371357765027600210270ustar00rootroot00000000000000# -*- coding: utf-8 -*- """ .. .. seealso:: `SPARQL Specification `_ Developers involved: * Ivan Herman * Sergio Fernández * Carlos Tejo Alonso * Alexey Zakhlestin Organizations involved: * `World Wide Web Consortium `_ * `Salzburg Research `_ * `Foundation CTIC `_ :license: `W3C® Software notice and license `_ :requires: `RDFLib `_ package. """ import urllib import urllib2 from urllib2 import urlopen as urlopener # don't change the name: tests override it import base64 import re import sys import warnings import json from KeyCaseInsensitiveDict import KeyCaseInsensitiveDict from SPARQLExceptions import QueryBadFormed, EndPointNotFound, EndPointInternalError, Unauthorized, URITooLong from SPARQLWrapper import __agent__ # From # The response body of a successful query operation with a 2XX response is either: # * SELECT and ASK: a SPARQL Results Document in XML, JSON, or CSV/TSV format. # * DESCRIBE and CONSTRUCT: an RDF graph serialized, for example, in the RDF/XML syntax, or an equivalent RDF graph serialization. # # Possible parameter keys and values... # Examples: # - ClioPatria: the SWI-Prolog Semantic Web Server # * Parameter key: "format" # * Parameter value must have one of these values: "rdf+xml", "json", "csv", "application/sparql-results+xml" or "application/sparql-results+json". # ################################################################################ # # - OpenLink Virtuoso # * Parameter key: "format" or "output" # * Parameter value, like directly: # "text/html" (HTML), "text/x-html+tr" (HTML (Faceted Browsing Links)), "application/vnd.ms-excel" # "application/sparql-results+xml" (XML), "application/sparql-results+json", (JSON) # "application/javascript" (Javascript), "text/turtle" (Turtle), "application/rdf+xml" (RDF/XML) # "text/plain" (N-Triples), "text/csv" (CSV), "text/tab-separated-values" (TSV) # * Parameter value, like indirectly: # "HTML" (alias text/html), "JSON" (alias application/sparql-results+json), "XML" (alias application/sparql-results+xml), "TURTLE" (alias text/rdf+n3), JavaScript (alias application/javascript) # See # # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml # For a ASK query type, the default return mimetype (if Accept: */* is sent) is text/html # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle # ################################################################################ # # - Fuseki (formerly there was Joseki) # * Uses: Parameters AND Content Negotiation # * Parameter key: "format" or "output" # * JSON-LD (application/ld+json): supported (in CONSTRUCT and DESCRIBE) # # * Parameter key: "format" or "output" # See Fuseki 1: https://github.com/apache/jena/blob/master/jena-fuseki1/src/main/java/org/apache/jena/fuseki/HttpNames.java # See Fuseki 2: https://github.com/apache/jena/blob/master/jena-arq/src/main/java/org/apache/jena/riot/web/HttpNames.java # * Fuseki 1 - Short names for "output=" : "json", "xml", "sparql", "text", "csv", "tsv", "thrift" # See # * Fuseki 2 - Short names for "output=" : "json", "xml", "sparql", "text", "csv", "tsv", "thrift" # See # If a non-expected short name is used, the server returns an "Error 400: Can't determine output serialization" # Valid alias for SELECT and ASK: "json", "xml", csv", "tsv" # Valid alias for DESCRIBE and CONSTRUCT: "json" (alias for json-ld ONLY in Fuseki2), "xml" # Valid mimetype for DESCRIBE and CONSTRUCT: "application/ld+json" # Default return mimetypes: For a SELECT and ASK query types, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json # Default return mimetypes: For a DESCRIBE and CONTRUCT query types, the default return mimetype (if Accept: */* is sent) is text/turtle # In case of a bad formed query, Fuseki1 returns 200 instead of 400. # ################################################################################ # # - Eclipse RDF4J # * Formerly known as OpenRDF Sesame # * Uses: ONLY Content Negotiation # * See # * See # * Parameter: If an unexpected parameter is used, the server ignores it. # # ** SELECT # *** application/sparql-results+xml (DEFAULT if Accept: */* is sent)) # *** application/sparql-results+json (also application/json) # *** text/csv # *** text/tab-separated-values # *** Other values: application/x-binary-rdf-results-table # # ** ASK # *** application/sparql-results+xml (DEFAULT if Accept: */* is sent)) # *** application/sparql-results+json # *** Other values: text/boolean # *** Not supported: text/csv # *** Not supported: text/tab-separated-values # # ** CONSTRUCT # *** application/rdf+xml # *** application/n-triples (DEFAULT if Accept: */* is sent) # *** text/turtle # *** text/n3 # *** application/ld+json # *** Other acceptable values: application/n-quads, application/rdf+json, application/trig, application/trix, application/x-binary-rdf # *** text/plain (returns application/n-triples) # *** text/rdf+n3 (returns text/n3) # *** text/x-nquads (returns application/n-quads) # # ** DESCRIBE # *** application/rdf+xml # *** application/n-triples (DEFAULT if Accept: */* is sent) # *** text/turtle # *** text/n3 # *** application/ld+json # *** Other acceptable values: application/n-quads, application/rdf+json, application/trig, application/trix, application/x-binary-rdf # *** text/plain (returns application/n-triples) # *** text/rdf+n3 (returns text/n3) # *** text/x-nquads (returns application/n-quads) # # Default return mimetypes: For a SELECT and ASK query types, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml # Default return mimetypes: For a DESCRIBE and CONTRUCT query types, the default return mimetype (if Accept: */* is sent) is application/n-triples # # ################################################################################ # # - RASQAL # * Parameter key: "results" # * Uses roqet as RDF query utility # For variable bindings, the values of FORMAT vary upon what Rasqal supports but include simple # for a simple text format (default), xml for the SPARQL Query Results XML format, csv for SPARQL CSV, # tsv for SPARQL TSV, rdfxml and turtle for RDF syntax formats, and json for a JSON version of the results. # # For RDF graph results, the values of FORMAT are ntriples (N-Triples, default), # rdfxml-abbrev (RDF/XML Abbreviated), rdfxml (RDF/XML), turtle (Turtle), # json (RDF/JSON resource centric), json-triples (RDF/JSON triples) or # rss-1.0 (RSS 1.0, also an RDF/XML syntax). # # See # ################################################################################ # # - Marklogic # * Uses content negotiation (no URL parameters). # * You can use following methods to query triples : # - SPARQL mode in Query Console. For details, see Querying Triples with SPARQL # - XQuery using the semantics functions, and Search API, or a combination of XQuery and SPARQL. For details, see Querying Triples with XQuery or JavaScript. # - HTTP via a SPARQL endpoint. For details, see Using Semantics with the REST Client API. # * Formats are specified as part of the HTTP Accept headers of the REST request. # - When you query the SPARQL endpoint with REST Client APIs, you can specify the result output format. # The response type format depends on the type of query and the MIME type in the HTTP Accept header. # - This table describes the MIME types and Accept Header/Output formats (MIME type) for different types of SPARQL queries. See and # SELECT "application/sparql-results+xml", "application/sparql-results+json", "text/html", "text/csv" # CONSTRUCT or DESCRIBE "application/n-triples", "application/rdf+json", "application/rdf+xml", "text/turtle", "text/n3", "application/n-quads", "application/trig" # ASK queries return a boolean (true or false). # ################################################################################ # # - AllegroGraph # * Uses only content negotiation (no URL parameters). # * The server always looks at the Accept header of a request, and tries to # generate a response in the format that the client asks for. If this fails, # a 406 response is returned. When no Accept, or an Accept of */* is specified, # the server prefers text/plain, in order to make it easy to explore the interface from a web browser. # * Accept header expected (values returned by server when a wrong header is sent): # ** SELECT # *** application/sparql-results+xml (DEFAULT if Accept: */* is sent) # *** application/sparql-results+json (and application/json) # *** text/csv # *** text/tab-separated-values # *** OTHERS: application/sparql-results+ttl, text/integer, application/x-lisp-structured-expression, text/table, application/processed-csv, text/simple-csv, application/x-direct-upis # # ** ASK # *** application/sparql-results+xml (DEFAULT if Accept: */* is sent) # *** application/sparql-results+json (and application/json) # *** Not supported: text/csv # *** Not supported: text/tab-separated-values # # ** CONSTRUCT # *** application/rdf+xml (DEFAULT if Accept: */* is sent) # *** text/rdf+n3 # *** OTHERS: text/integer, application/json, text/plain, text/x-nquads, application/trix, text/table, application/x-direct-upis # # ** DESCRIBE # *** application/rdf+xml (DEFAULT if Accept: */* is sent) # *** text/rdf+n3 # # See # ################################################################################ # # - 4store. Code repository documentation # * Uses: Parameters AND Content Negotiation # * Parameter key: "output" # * Parameter value: alias. If an unexpected alias is used, the server is not working properly # * JSON-LD: NOT supported # # ** SELECT # *** application/sparql-results+xml (alias xml) (DEFAULT if Accept: */* is sent)) # *** application/sparql-results+json or application/json (alias json) # *** text/csv (alias csv) # *** text/tab-separated-values (alias tsv). Returns "text/plain" in GET. # *** Other values: text/plain, application/n-triples # # ** ASK # *** application/sparql-results+xml (alias xml) (DEFAULT if Accept: */* is sent)) # *** application/sparql-results+json or application/json (alias json) # *** text/csv (alias csv) # *** text/tab-separated-values (alias tsv). Returns "text/plain" in GET. # *** Other values: text/plain, application/n-triples # # ** CONSTRUCT # *** application/rdf+xml (alias xml) (DEFAULT if Accept: */* is sent) # *** text/turtle (alias "text") # # ** DESCRIBE # *** application/rdf+xml (alias xml) (DEFAULT if Accept: */* is sent) # *** text/turtle (alias "text") # # Valid alias for SELECT and ASK: "json", "xml", csv", "tsv" (also "text" and "ascii") # Valid alias for DESCRIBE and CONSTRUCT: "xml", "text" (for turtle) # Default return mimetypes: For a SELECT and ASK query types, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml # Default return mimetypes: For a DESCRIBE and CONTRUCT query types, the default return mimetype (if Accept: */* is sent) is application/rdf+xml # # ################################################################################ # # - Blazegraph & NanoSparqlServer # * Formerly known as Bigdata # * Uses: Parameters AND Content Negotiation # * Parameter key: "format" (available since version 1.4.0). Setting this parameter will override any Accept Header that is present. # * Parameter value: alias. If an unexpected alias is used, the server is not working properly # # ** SELECT # *** application/sparql-results+xml (alias xml) (DEFAULT if Accept: */* is sent)) # *** application/sparql-results+json or application/json (alias json) # *** text/csv # *** text/tab-separated-values # *** Other values: application/x-binary-rdf-results-table # # ** ASK # *** application/sparql-results+xml (alias xml) (DEFAULT if Accept: */* is sent)) # *** application/sparql-results+json or application/json (alias json) # # ** CONSTRUCT # *** application/rdf+xml (alias xml) (DEFAULT if Accept: */* is sent) # *** text/turtle (returns text/n3) # *** text/n3 # # ** DESCRIBE # *** application/rdf+xml (alias xml) (DEFAULT if Accept: */* is sent) # *** text/turtle (returns text/n3) # *** text/n3 # # Valid alias for SELECT and ASK: "xml", "json" # Valid alias for DESCRIBE and CONSTRUCT: "xml", "json" (but it returns unexpected "application/sparql-results+json") # Default return mimetypes: For a SELECT and ASK query types, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml # Default return mimetypes: For a DESCRIBE and CONTRUCT query types, the default return mimetype (if Accept: */* is sent) is application/rdf+xml # ################################################################################ # # - GraphDB # * Formerly known as OWLIM (OWLIM-Lite, OWLIM-SE) # * Uses: Only Content Negotiation. # * If the Accept value is not within the expected ones, the server returns a 406 "No acceptable file format found." # # ** SELECT # *** DEFAULT (if Accept: */* is sent): text/csv # *** application/sparql-results+xml, application/xml (.srx file) # *** application/sparql-results+json, application/json (.srj file) # *** text/csv (DEFAULT if Accept: */* is sent) # *** text/tab-separated-values # # ** ASK # *** DEFAULT (if Accept: */* is sent): application/sparql-results+json # *** application/sparql-results+xml, application/xml (.srx file) # *** application/sparql-results+json (DEFAULT if Accept: */* is sent), application/json (.srj file) # *** NOT supported: text/csv, text/tab-separated-values # # ** CONSTRUCT # *** DEFAULT (if Accept: */* is sent): application/n-triples # *** application/rdf+xml, application/xml (.rdf file) # *** text/turtle (.ttl file) # *** application/n-triples (.nt file) (DEFAULT if Accept: */* is sent) # *** text/n3, text/rdf+n3 (.n3 file) # *** application/ld+json (.jsonld file) # # ** DESCRIBE # *** DEFAULT (if Accept: */* is sent): application/n-triples # *** application/rdf+xml, application/xml (.rdf file) # *** text/turtle (.ttl file) # *** application/n-triples (.nt file) (DEFAULT if Accept: */* is sent) # *** text/n3, text/rdf+n3 (.n3 file) # *** application/ld+json (.jsonld file) # ################################################################################ # # - Stardog (the doc looks outdated) # * Uses: ONLY Content Negotiation # * Parameter: If an unexpected parameter is used, the server ignores it. # # ** SELECT # *** application/sparql-results+xml (DEFAULT if Accept: */* is sent)) # *** application/sparql-results+json # *** text/csv # *** text/tab-separated-values # *** Other values: application/x-binary-rdf-results-table # # ** ASK # *** application/sparql-results+xml (DEFAULT if Accept: */* is sent)) # *** application/sparql-results+json # *** Other values: text/boolean # *** Not supported: text/csv # *** Not supported: text/tab-separated-values # # ** CONSTRUCT # *** application/rdf+xml # *** text/turtle (DEFAULT if Accept: */* is sent) # *** text/n3 # *** application/ld+json # *** Other acceptable values: application/n-triples, application/x-turtle, application/trig, application/trix, application/n-quads # # ** DESCRIBE # *** application/rdf+xml # *** text/turtle (DEFAULT if Accept: */* is sent) # *** text/n3 # *** application/ld+json # *** Other acceptable values: application/n-triples, application/x-turtle, application/trig, application/trix, application/n-quads # # Default return mimetypes: For a SELECT and ASK query types, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml # Default return mimetypes: For a DESCRIBE and CONTRUCT query types, the default return mimetype (if Accept: */* is sent) is text/turtle # ################################################################################ # alias XML = "xml" """to be used to set the return format to ``XML`` (``SPARQL Query Results XML`` format or ``RDF/XML``, depending on the query type). **This is the default**.""" JSON = "json" """to be used to set the return format to ``JSON``.""" JSONLD = "json-ld" """to be used to set the return format to ``JSON-LD``.""" TURTLE = "turtle" """to be used to set the return format to ``Turtle``.""" N3 = "n3" """to be used to set the return format to ``N3`` (for most of the SPARQL services this is equivalent to Turtle).""" RDF = "rdf" """to be used to set the return ``RDF Graph``.""" RDFXML = "rdf+xml" """to be used to set the return format to ``RDF/XML`` explicitly.""" CSV = "csv" """to be used to set the return format to ``CSV``""" TSV = "tsv" """to be used to set the return format to ``TSV``""" _allowedFormats = [JSON, XML, TURTLE, N3, RDF, RDFXML, CSV, TSV] # Possible HTTP methods GET = "GET" """to be used to set HTTP method ``GET``. **This is the default**.""" POST = "POST" """to be used to set HTTP method ``POST``.""" _allowedRequests = [POST, GET] # Possible HTTP Authentication methods BASIC = "BASIC" """to be used to set ``BASIC`` HTTP Authentication method.""" DIGEST = "DIGEST" """to be used to set ``DIGEST`` HTTP Authentication method.""" _allowedAuth = [BASIC, DIGEST] # Possible SPARQL/SPARUL query type (aka SPARQL Query forms) SELECT = "SELECT" """to be used to set the query type to ``SELECT``. This is, usually, determined automatically.""" CONSTRUCT = "CONSTRUCT" """to be used to set the query type to ``CONSTRUCT``. This is, usually, determined automatically.""" ASK = "ASK" """to be used to set the query type to ``ASK``. This is, usually, determined automatically.""" DESCRIBE = "DESCRIBE" """to be used to set the query type to ``DESCRIBE``. This is, usually, determined automatically.""" INSERT = "INSERT" """to be used to set the query type to ``INSERT``. This is, usually, determined automatically.""" DELETE = "DELETE" """to be used to set the query type to ``DELETE``. This is, usually, determined automatically.""" CREATE = "CREATE" """to be used to set the query type to ``CREATE``. This is, usually, determined automatically.""" CLEAR = "CLEAR" """to be used to set the query type to ``CLEAR``. This is, usually, determined automatically.""" DROP = "DROP" """to be used to set the query type to ``DROP``. This is, usually, determined automatically.""" LOAD = "LOAD" """to be used to set the query type to ``LOAD``. This is, usually, determined automatically.""" COPY = "COPY" """to be used to set the query type to ``COPY``. This is, usually, determined automatically.""" MOVE = "MOVE" """to be used to set the query type to ``MOVE``. This is, usually, determined automatically.""" ADD = "ADD" """to be used to set the query type to ``ADD``. This is, usually, determined automatically.""" _allowedQueryTypes = [SELECT, CONSTRUCT, ASK, DESCRIBE, INSERT, DELETE, CREATE, CLEAR, DROP, LOAD, COPY, MOVE, ADD] # Possible methods to perform requests URLENCODED = "urlencoded" """to be used to set **URL encode** as the encoding method for the request. This is, usually, determined automatically.""" POSTDIRECTLY = "postdirectly" """to be used to set **POST directly** as the encoding method for the request. This is, usually, determined automatically.""" _REQUEST_METHODS = [URLENCODED, POSTDIRECTLY] # Possible output format (mime types) that can be converted by the local script. Unfortunately, # it does not work by simply setting the return format, because there is still a certain level of confusion # among implementations. # For example, Joseki returns application/javascript and not the sparql-results+json thing that is required... # Ie, alternatives should be given... # Andy Seaborne told me (June 2007) that the right return format is now added to his CVS, ie, future releases of # joseki will be o.k., too. The situation with turtle and n3 is even more confusing because the text/n3 and text/turtle # mime types have just been proposed and not yet widely used... _SPARQL_DEFAULT = ["application/sparql-results+xml", "application/rdf+xml", "*/*"] _SPARQL_XML = ["application/sparql-results+xml"] _SPARQL_JSON = ["application/sparql-results+json", "application/json", "text/javascript", "application/javascript"] # VIVO server returns "application/javascript" _RDF_XML = ["application/rdf+xml"] _RDF_TURTLE = ["application/turtle", "text/turtle"] _RDF_N3 = _RDF_TURTLE + ["text/rdf+n3", "application/n-triples", "application/n3", "text/n3"] _RDF_JSONLD = ["application/ld+json", "application/x-json+ld"] _CSV = ["text/csv"] _TSV = ["text/tab-separated-values"] _XML = ["application/xml"] _ALL = ["*/*"] _RDF_POSSIBLE = _RDF_XML + _RDF_N3 + _XML _SPARQL_PARAMS = ["query"] try: import rdflib_jsonld _allowedFormats.append(JSONLD) _RDF_POSSIBLE = _RDF_POSSIBLE + _RDF_JSONLD except ImportError: #warnings.warn("JSON-LD disabled because no suitable support has been found", RuntimeWarning) pass # This is very ugly. The fact is that the key for the choice of the output format is not defined. # Virtuoso uses 'format', joseki uses 'output', rasqual seems to use "results", etc. Lee Feigenbaum # told me that virtuoso also understand 'output' these days, so I removed 'format'. I do not have # info about the others yet, ie, for the time being I keep the general mechanism. Hopefully, in a # future release, I can get rid of that. However, these processors are (hopefully) oblivious to the # parameters they do not understand. So: just repeat all possibilities in the final URI. UGLY!!!!!!! _returnFormatSetting = ["format", "output", "results"] ####################################################################################################### class SPARQLWrapper(object): """ Wrapper around an online access to a SPARQL Web entry point. The same class instance can be reused for subsequent queries. The values of the base Graph URI, return formats, etc, are retained from one query to the next (in other words, only the query string changes). The instance can also be reset to its initial values using the :meth:`resetQuery` method. :ivar endpoint: SPARQL endpoint's URI. :vartype endpoint: string :ivar updateEndpoint: SPARQL endpoint's URI for SPARQL Update operations (if it's a different one). The **default** value is ``None``. :vartype updateEndpoint: string :ivar agent: The User-Agent for the HTTP request header. The **default** value is an autogenerated string using the SPARQLWrapper version code. :vartype agent: string :ivar _defaultGraph: URI for the default graph. The value can be set either via an explicit call :func:`addParameter("default-graph-uri", uri)` or as part of the query string. The **default** value is ``None``. :vartype _defaultGraph: string :ivar user: The username of the credentials for querying the current endpoint. The value can be set an explicit call :func:`setCredentials`. The **default** value is ``None``. :vartype user: string :ivar passwd: The password of the credentials for querying the current endpoint. The value can be set an explicit call :func:`setCredentials`. The **default** value is ``None``. :vartype passwd: string :ivar http_auth: HTTP Authentication type. The **default** value is :data:`BASIC`. Possible values are :data:`BASIC` or :data:`DIGEST`. It is used only in case the credentials are set. :vartype http_auth: string :ivar onlyConneg: Option for allowing (or not) **only** HTTP Content Negotiation (so dismiss the use of HTTP parameters). The default value is ``False``. :vartype onlyConneg: boolean :ivar customHttpHeaders: Custom HTTP Headers to be included in the request. It is a dictionary where keys are the header field and values are the header values. **Important**: These headers override previous values (including ``Content-Type``, ``User-Agent``, ``Accept`` and ``Authorization`` if they are present). :vartype customHttpHeaders: dict :ivar timeout: The timeout (in seconds) to use for querying the endpoint. :vartype timeout: int :ivar queryString: The SPARQL query text. :vartype queryString: string :ivar queryType: The type of SPARQL query (aka SPARQL query form), like :data:`CONSTRUCT`, :data:`SELECT`, :data:`ASK`, :data:`DESCRIBE`, :data:`INSERT`, :data:`DELETE`, :data:`CREATE`, :data:`CLEAR`, :data:`DROP`, :data:`LOAD`, :data:`COPY`, :data:`MOVE` or :data:`ADD` (constants in this module). :vartype queryType: string :ivar returnFormat: The return format.\ No local check is done, so the parameter is simply sent to the endpoint. Eg, if the value is set to :data:`JSON` and a construct query is issued, it is up to the endpoint to react or not, this wrapper does not check.\ The possible values are :data:`JSON`, :data:`XML`, :data:`TURTLE`, :data:`N3`, :data:`RDF`, :data:`RDFXML`, :data:`CSV`, :data:`TSV`, :data:`JSONLD` (constants in this module).\ The **default** value is :data:`XML`. :vartype returnFormat: string :ivar requestMethod: The request method for query or update operations. The possibles values are URL-encoded (:data:`URLENCODED`) or POST directly (:data:`POSTDIRECTLY`). :vartype requestMethod: string :ivar method: The invocation method (HTTP verb). The **default** value is :data:`GET`, but it can be set to :data:`POST`. :vartype method: string :ivar parameters: The parameters of the request (key/value pairs in a dictionary). :vartype parameters: dict :ivar _defaultReturnFormat: The default return format. It is used in case the same class instance is reused for subsequent queries. :vartype _defaultReturnFormat: string :cvar prefix_pattern: regular expression used to remove base/prefixes in the process of determining the query type. :vartype prefix_pattern: :class:`re.RegexObject`, a compiled regular expression. See the :mod:`re` module of Python :cvar pattern: regular expression used to determine whether a query (without base/prefixes) is of type :data:`CONSTRUCT`, :data:`SELECT`, :data:`ASK`, :data:`DESCRIBE`, :data:`INSERT`, :data:`DELETE`, :data:`CREATE`, :data:`CLEAR`, :data:`DROP`, :data:`LOAD`, :data:`COPY`, :data:`MOVE` or :data:`ADD`. :vartype pattern: :class:`re.RegexObject`, a compiled regular expression. See the :mod:`re` module of Python :cvar comments_pattern: regular expression used to remove comments from a query. :vartype comments_pattern: :class:`re.RegexObject`, a compiled regular expression. See the :mod:`re` module of Python """ prefix_pattern = re.compile(r"((?P(\s*BASE\s*<.*?>)\s*)|(?P(\s*PREFIX\s+.+:\s*<.*?>)\s*))*") # Maybe the future name could be queryType_pattern pattern = re.compile(r"(?P(CONSTRUCT|SELECT|ASK|DESCRIBE|INSERT|DELETE|CREATE|CLEAR|DROP|LOAD|COPY|MOVE|ADD))", re.VERBOSE | re.IGNORECASE) comments_pattern = re.compile(r"(^|\n)\s*#.*?\n") def __init__(self, endpoint, updateEndpoint=None, returnFormat=XML, defaultGraph=None, agent=__agent__): """ Class encapsulating a full SPARQL call. :param endpoint: SPARQL endpoint's URI. :type endpoint: string :param updateEndpoint: SPARQL endpoint's URI for update operations (if it's a different one). The **default** value is ``None``. :type updateEndpoint: string :param returnFormat: The return format.\ No local check is done, so the parameter is simply sent to the endpoint. Eg, if the value is set to :data:`JSON` and a construct query is issued, it is up to the endpoint to react or not, this wrapper does not check.\ The possible values are :data:`JSON`, :data:`XML`, :data:`TURTLE`, :data:`N3`, :data:`RDF`, :data:`RDFXML`, :data:`CSV`, :data:`TSV`, :data:`JSONLD` (constants in this module).\ The **default** value is :data:`XML`. :param defaultGraph: URI for the default graph. The value can be set either via an explicit call :func:`addParameter("default-graph-uri", uri)` or as part of the query string. The **default** value is ``None``. :type defaultGraph: string :param agent: The User-Agent for the HTTP request header. The **default** value is an autogenerated string using the SPARQLWrapper version number. :type agent: string """ self.endpoint = endpoint self.updateEndpoint = updateEndpoint if updateEndpoint else endpoint self.agent = agent self.user = None self.passwd = None self.http_auth = BASIC self._defaultGraph = defaultGraph self.onlyConneg = False # Only Content Negotiation self.customHttpHeaders = {} if returnFormat in _allowedFormats: self._defaultReturnFormat = returnFormat else: self._defaultReturnFormat = XML self.resetQuery() def resetQuery(self): """Reset the query, ie, return format, method, query, default or named graph settings, etc, are reset to their default values. This includes the default values for parameters, method, timeout or requestMethod. """ self.parameters = {} if self._defaultGraph: self.addParameter("default-graph-uri", self._defaultGraph) self.returnFormat = self._defaultReturnFormat self.method = GET self.setQuery("""SELECT * WHERE{ ?s ?p ?o }""") self.timeout = None self.requestMethod = URLENCODED def setReturnFormat(self, format): """Set the return format. If the one set is not an allowed value, the setting is ignored. :param format: Possible values are :data:`JSON`, :data:`XML`, :data:`TURTLE`, :data:`N3`, :data:`RDF`, :data:`RDFXML`, :data:`CSV`, :data:`TSV`, :data:`JSONLD` (constants in this module). All other cases are ignored. :type format: string :raises ValueError: If :data:`JSONLD` is tried to set and the current instance does not support ``JSON-LD``. """ if format in _allowedFormats: self.returnFormat = format elif format == JSONLD: raise ValueError("Current instance does not support JSON-LD; you might want to install the rdflib-jsonld package.") else: warnings.warn("Ignore format '%s'; current instance supports: %s." %(format, ", ".join(_allowedFormats)), SyntaxWarning) def supportsReturnFormat(self, format): """Check if a return format is supported. :param format: Possible values are :data:`JSON`, :data:`XML`, :data:`TURTLE`, :data:`N3`, :data:`RDF`, :data:`RDFXML`, :data:`CSV`, :data:`TSV`, :data:`JSONLD` (constants in this module). All other cases are ignored. :type format: string :return: Returns ``True`` if the return format is supported, otherwise ``False``. :rtype: bool """ return (format in _allowedFormats) def setTimeout(self, timeout): """Set the timeout (in seconds) to use for querying the endpoint. :param timeout: Timeout in seconds. :type timeout: int """ self.timeout = int(timeout) def setOnlyConneg(self, onlyConneg): """Set this option for allowing (or not) only HTTP Content Negotiation (so dismiss the use of HTTP parameters). .. versionadded:: 1.8.1 :param onlyConneg: ``True`` if **only** HTTP Content Negotiation is allowed; ``False`` if HTTP parameters are used. :type onlyConneg: bool """ self.onlyConneg = onlyConneg def setRequestMethod(self, method): """Set the internal method to use to perform the request for query or update operations, either URL-encoded (:data:`URLENCODED`) or POST directly (:data:`POSTDIRECTLY`). Further details at `query operation in SPARQL `_ and `update operation in SPARQL Update `_. :param method: Possible values are :data:`URLENCODED` (URL-encoded) or :data:`POSTDIRECTLY` (POST directly). All other cases are ignored. :type method: string """ if method in _REQUEST_METHODS: self.requestMethod = method else: warnings.warn("invalid update method '%s'" % method, RuntimeWarning) def addDefaultGraph(self, uri): """ Add a default graph URI. .. deprecated:: 1.6.0 Use :func:`addParameter("default-graph-uri", uri)` instead of this method. :param uri: URI of the default graph. :type uri: string """ self.addParameter("default-graph-uri", uri) def addNamedGraph(self, uri): """ Add a named graph URI. .. deprecated:: 1.6.0 Use :func:`addParameter("named-graph-uri", uri)` instead of this method. :param uri: URI of the named graph. :type uri: string """ self.addParameter("named-graph-uri", uri) def addExtraURITag(self, key, value): """ Some SPARQL endpoints require extra key value pairs. E.g., in virtuoso, one would add ``should-sponge=soft`` to the query forcing virtuoso to retrieve graphs that are not stored in its local database. Alias of :func:`addParameter` method. .. deprecated:: 1.6.0 Use :func:`addParameter(key, value)` instead of this method :param key: key of the query part. :type key: string :param value: value of the query part. :type value: string """ self.addParameter(key, value) def addCustomParameter(self, name, value): """ Method is kept for backwards compatibility. Historically, it "replaces" parameters instead of adding. .. deprecated:: 1.6.0 Use :func:`addParameter(key, value)` instead of this method :param name: name. :type name: string :param value: value. :type value: string :return: Returns ``True`` if the adding has been accomplished, otherwise ``False``. :rtype: bool """ self.clearParameter(name) return self.addParameter(name, value) def addParameter(self, name, value): """ Some SPARQL endpoints allow extra key value pairs. E.g., in virtuoso, one would add ``should-sponge=soft`` to the query forcing virtuoso to retrieve graphs that are not stored in its local database. If the parameter :attr:`query` is tried to be set, this intent is dismissed. Returns a boolean indicating if the set has been accomplished. :param name: name. :type name: string :param value: value. :type value: string :return: Returns ``True`` if the adding has been accomplished, otherwise ``False``. :rtype: bool """ if name in _SPARQL_PARAMS: return False else: if name not in self.parameters: self.parameters[name] = [] self.parameters[name].append(value) return True def addCustomHttpHeader(self, httpHeaderName, httpHeaderValue): """ Add a custom HTTP header (this method can override all HTTP headers). **Important**: Take into account that each previous value for the header field names ``Content-Type``, ``User-Agent``, ``Accept`` and ``Authorization`` would be overriden if the header field name is present as value of the parameter :attr:`httpHeaderName`. .. versionadded:: 1.8.2 :param httpHeaderName: The header field name. :type httpHeaderName: string :param httpHeaderValue: The header field value. :type httpHeaderValue: string """ self.customHttpHeaders[httpHeaderName] = httpHeaderValue def clearCustomHttpHeader(self, httpHeaderName): """ Clear the values of a custom HTTP Header previously set. Returns a boolean indicating if the clearing has been accomplished. .. versionadded:: 1.8.2 :param httpHeaderName: HTTP header name. :type httpHeaderName: string :return: Returns ``True`` if the clearing has been accomplished, otherwise ``False``. :rtype: bool """ try: del self.customHttpHeaders[httpHeaderName] return True except KeyError: return False def clearParameter(self, name): """ Clear the values of a concrete parameter. Returns a boolean indicating if the clearing has been accomplished. :param name: name :type name: string :return: Returns ``True`` if the clearing has been accomplished, otherwise ``False``. :rtype: bool """ if name in _SPARQL_PARAMS: return False else: try: del self.parameters[name] return True except KeyError: return False def setCredentials(self, user, passwd, realm="SPARQL"): """ Set the credentials for querying the current endpoint. :param user: username. :type user: string :param passwd: password. :type passwd: string :param realm: realm. Only used for :data:`DIGEST` authentication. The **default** value is ``SPARQL`` :type realm: string .. versionchanged:: 1.8.3 Added :attr:`realm` parameter. """ self.user = user self.passwd = passwd self.realm = realm def setHTTPAuth(self, auth): """ Set the HTTP Authentication type. Possible values are :class:`BASIC` or :class:`DIGEST`. :param auth: auth type. :type auth: string :raises TypeError: If the :attr:`auth` parameter is not an string. :raises ValueError: If the :attr:`auth` parameter has not one of the valid values: :class:`BASIC` or :class:`DIGEST`. """ if not isinstance(auth, str): raise TypeError('setHTTPAuth takes a string') elif auth.upper() in _allowedAuth: self.http_auth = auth.upper() else: valid_types = ", ".join(_allowedAuth) raise ValueError("Value should be one of {0}".format(valid_types)) def setQuery(self, query): """ Set the SPARQL query text. .. note:: No check is done on the validity of the query (syntax or otherwise) by this module, except for testing the query type (SELECT, ASK, etc). Syntax and validity checking is done by the SPARQL service itself. :param query: query text. :type query: string :raises TypeError: If the :attr:`query` parameter is not an unicode-string or utf-8 encoded byte-string. """ if sys.version < '3': # have to write it like this, for 2to3 compatibility if isinstance(query, unicode): pass elif isinstance(query, str): query = query.decode('utf-8') else: raise TypeError('setQuery takes either unicode-strings or utf-8 encoded byte-strings') else: if isinstance(query, str): pass elif isinstance(query, bytes): query = query.decode('utf-8') else: raise TypeError('setQuery takes either unicode-strings or utf-8 encoded byte-strings') self.queryString = query self.queryType = self._parseQueryType(query) def _parseQueryType(self, query): """ Internal method for parsing the SPARQL query and return its type (ie, :data:`SELECT`, :data:`ASK`, etc). .. note:: The method returns :data:`SELECT` if nothing is specified. This is just to get all other methods running; in fact, this means that the query is erroneous, because the query must be, according to the SPARQL specification. The SPARQL endpoint should raise an exception (via :mod:`urllib`) for such syntax error. :param query: query text. :type query: string :return: the type of SPARQL query (aka SPARQL query form). :rtype: string """ try: query = query if (isinstance(query, str)) else query.encode('ascii', 'ignore') query = self._cleanComments(query) query_for_queryType = re.sub(self.prefix_pattern, "", query.strip()) r_queryType = self.pattern.search(query_for_queryType).group("queryType").upper() except AttributeError: warnings.warn("not detected query type for query '%s'" % query.replace("\n", " "), RuntimeWarning) r_queryType = None if r_queryType in _allowedQueryTypes: return r_queryType else: #raise Exception("Illegal SPARQL Query; must be one of SELECT, ASK, DESCRIBE, or CONSTRUCT") warnings.warn("unknown query type '%s'" % r_queryType, RuntimeWarning) return SELECT def setMethod(self, method): """Set the invocation method. By default, this is :data:`GET`, but can be set to :data:`POST`. :param method: should be either :data:`GET` or :data:`POST`. Other cases are ignored. :type method: string """ if method in _allowedRequests: self.method = method def setUseKeepAlive(self): """Make :mod:`urllib2` use keep-alive. :raises ImportError: when could not be imported ``keepalive.HTTPHandler``. """ try: from keepalive import HTTPHandler if urllib2._opener and any(isinstance(h, HTTPHandler) for h in urllib2._opener.handlers): # already installed return keepalive_handler = HTTPHandler() opener = urllib2.build_opener(keepalive_handler) urllib2.install_opener(opener) except ImportError: warnings.warn("keepalive support not available, so the execution of this method has no effect") def isSparqlUpdateRequest(self): """ Returns ``True`` if SPARQLWrapper is configured for executing SPARQL Update request. :return: Returns ``True`` if SPARQLWrapper is configured for executing SPARQL Update request. :rtype: bool """ return self.queryType in [INSERT, DELETE, CREATE, CLEAR, DROP, LOAD, COPY, MOVE, ADD] def isSparqlQueryRequest(self): """ Returns ``True`` if SPARQLWrapper is configured for executing SPARQL Query request. :return: Returns ``True`` if SPARQLWrapper is configured for executing SPARQL Query request. :rtype: bool """ return not self.isSparqlUpdateRequest() def _cleanComments(self, query): """ Internal method for returning the query after all occurrence of singleline comments are removed (issues #32 and #77). :param query: The query. :type query: string :return: the query after all occurrence of singleline comments are removed. :rtype: string """ return re.sub(self.comments_pattern, "\n\n", query) def _getRequestEncodedParameters(self, query=None): """ Internal method for getting the request encoded parameters. :param query: a tuple of two items. The first item can be the string \ ``query`` (for :data:`SELECT`, :data:`DESCRIBE`, :data:`ASK`, :data:`CONSTRUCT` query) or the string ``update`` \ (for SPARQL Update queries, like :data:`DELETE` or :data:`INSERT`). The second item of the tuple \ is the query string itself. :type query: tuple :return: the request encoded parameters. :rtype: string """ query_parameters = self.parameters.copy() # in case of query = tuple("query"/"update", queryString) if query and (isinstance(query, tuple)) and len(query) == 2: query_parameters[query[0]] = [query[1]] if not self.isSparqlUpdateRequest(): # This is very ugly. The fact is that the key for the choice of the output format is not defined. # Virtuoso uses 'format',sparqler uses 'output' # However, these processors are (hopefully) oblivious to the parameters they do not understand. # So: just repeat all possibilities in the final URI. UGLY!!!!!!! if not self.onlyConneg: for f in _returnFormatSetting: query_parameters[f] = [self.returnFormat] # Virtuoso is not supporting a correct Accept header and an unexpected "output"/"format" parameter value. It returns a 406. # "tsv", "rdf+xml" and "json-ld" are not supported as a correct "output"/"format" parameter value but "text/tab-separated-values" or "application/rdf+xml" are a valid values, # and there is no problem to send both (4store does not support unexpected values). if self.returnFormat in [TSV, JSONLD, RDFXML]: acceptHeader = self._getAcceptHeader() # to obtain the mime-type "text/tab-separated-values" or "application/rdf+xml" if "*/*" in acceptHeader: acceptHeader = "" # clear the value in case of "*/*" query_parameters[f] += [acceptHeader] pairs = ( "%s=%s" % ( urllib.quote_plus(param.encode('UTF-8'), safe='/'), urllib.quote_plus(value.encode('UTF-8'), safe='/') ) for param, values in query_parameters.items() for value in values ) return '&'.join(pairs) def _getAcceptHeader(self): """ Internal method for getting the HTTP Accept Header. .. seealso:: `Hypertext Transfer Protocol -- HTTP/1.1 - Header Field Definitions `_ """ if self.queryType in [SELECT, ASK]: if self.returnFormat == XML: acceptHeader = ",".join(_SPARQL_XML) elif self.returnFormat == JSON: acceptHeader = ",".join(_SPARQL_JSON) elif self.returnFormat == CSV: # Allowed for SELECT and ASK (https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-success) but only described for SELECT (https://www.w3.org/TR/sparql11-results-csv-tsv/) acceptHeader = ",".join(_CSV) elif self.returnFormat == TSV: # Allowed for SELECT and ASK (https://www.w3.org/TR/2013/REC-sparql11-protocol-20130321/#query-success) but only described for SELECT (https://www.w3.org/TR/sparql11-results-csv-tsv/) acceptHeader = ",".join(_TSV) else: acceptHeader = ",".join(_ALL) warnings.warn("Sending Accept header '*/*' because unexpected returned format '%s' in a '%s' SPARQL query form" % (self.returnFormat, self.queryType), RuntimeWarning) elif self.queryType in [CONSTRUCT, DESCRIBE]: if self.returnFormat == TURTLE: acceptHeader = ",".join(_RDF_TURTLE) elif self.returnFormat == N3: acceptHeader = ",".join(_RDF_N3) elif self.returnFormat == XML or self.returnFormat == RDFXML: acceptHeader = ",".join(_RDF_XML) elif self.returnFormat == JSONLD and JSONLD in _allowedFormats: acceptHeader = ",".join(_RDF_JSONLD) else: acceptHeader = ",".join(_ALL) warnings.warn("Sending Accept header '*/*' because unexpected returned format '%s' in a '%s' SPARQL query form" % (self.returnFormat, self.queryType), RuntimeWarning) elif self.queryType in [INSERT, DELETE, CREATE, CLEAR, DROP, LOAD, COPY, MOVE, ADD]: if self.returnFormat == XML: acceptHeader = ",".join(_SPARQL_XML) elif self.returnFormat == JSON: acceptHeader = ",".join(_SPARQL_JSON) else: acceptHeader = ",".join(_ALL) else: acceptHeader = "*/*" return acceptHeader def _createRequest(self): """Internal method to create request according a HTTP method. Returns a :class:`urllib2.Request` object of the :mod:`urllib2` Python library :raises NotImplementedError: If the HTTP authentification method is not one of the valid values: :data:`BASIC` or :data:`DIGEST`. :return: request a :class:`urllib2.Request` object of the :mod:`urllib2` Python library """ request = None if self.isSparqlUpdateRequest(): #protocol details at http://www.w3.org/TR/sparql11-protocol/#update-operation uri = self.updateEndpoint if self.method != POST: warnings.warn("update operations MUST be done by POST") if self.requestMethod == POSTDIRECTLY: request = urllib2.Request(uri + "?" + self._getRequestEncodedParameters()) request.add_header("Content-Type", "application/sparql-update") request.data = self.queryString.encode('UTF-8') else: # URL-encoded request = urllib2.Request(uri) request.add_header("Content-Type", "application/x-www-form-urlencoded") request.data = self._getRequestEncodedParameters(("update", self.queryString)).encode('ascii') else: #protocol details at http://www.w3.org/TR/sparql11-protocol/#query-operation uri = self.endpoint if self.method == POST: if self.requestMethod == POSTDIRECTLY: request = urllib2.Request(uri + "?" + self._getRequestEncodedParameters()) request.add_header("Content-Type", "application/sparql-query") request.data = self.queryString.encode('UTF-8') else: # URL-encoded request = urllib2.Request(uri) request.add_header("Content-Type", "application/x-www-form-urlencoded") request.data = self._getRequestEncodedParameters(("query", self.queryString)).encode('ascii') else: # GET request = urllib2.Request(uri + "?" + self._getRequestEncodedParameters(("query", self.queryString))) request.add_header("User-Agent", self.agent) request.add_header("Accept", self._getAcceptHeader()) if self.user and self.passwd: if self.http_auth == BASIC: credentials = "%s:%s" % (self.user, self.passwd) request.add_header("Authorization", "Basic %s" % base64.b64encode(credentials.encode('utf-8')).decode('utf-8')) elif self.http_auth == DIGEST: realm = self.realm pwd_mgr = urllib2.HTTPPasswordMgr() pwd_mgr.add_password(realm, uri, self.user, self.passwd) opener = urllib2.build_opener() opener.add_handler(urllib2.HTTPDigestAuthHandler(pwd_mgr)) urllib2.install_opener(opener) else: valid_types = ", ".join(_allowedAuth) raise NotImplementedError("Expecting one of: {0}, but received: {1}".format(valid_types, self.http_auth)) # The header field name is capitalized in the request.add_header method. for customHttpHeader in self.customHttpHeaders: request.add_header(customHttpHeader, self.customHttpHeaders[customHttpHeader]) return request def _query(self): """Internal method to execute the query. Returns the output of the :func:`urllib2.urlopen` method of the :mod:`urllib2` Python library :return: tuples with the raw request plus the expected format. :raises QueryBadFormed: If the HTTP return code is ``400``. :raises Unauthorized: If the HTTP return code is ``401``. :raises EndPointNotFound: If the HTTP return code is ``404``. :raises URITooLong: If the HTTP return code is ``414``. :raises EndPointInternalError: If the HTTP return code is ``500``. :raises urllib2.HTTPError: If the HTTP return code is different to ``400``, ``401``, ``404``, ``414``, ``500``. """ request = self._createRequest() try: if self.timeout: response = urlopener(request, timeout=self.timeout) else: response = urlopener(request) return response, self.returnFormat except urllib2.HTTPError as e: if e.code == 400: raise QueryBadFormed(e.read()) elif e.code == 404: raise EndPointNotFound(e.read()) elif e.code == 401: raise Unauthorized(e.read()) elif e.code == 414: raise URITooLong(e.read()) elif e.code == 500: raise EndPointInternalError(e.read()) else: raise e def query(self): """ Execute the query. Exceptions can be raised if either the URI is wrong or the HTTP sends back an error (this is also the case when the query is syntactically incorrect, leading to an HTTP error sent back by the SPARQL endpoint). The usual urllib2 exceptions are raised, which therefore cover possible SPARQL errors, too. Note that some combinations of return formats and query types may not make sense. For example, a SELECT query with Turtle response is meaningless (the output of a SELECT is not a Graph), or a CONSTRUCT query with JSON output may be a problem because, at the moment, there is no accepted JSON serialization of RDF (let alone one implemented by SPARQL endpoints). In such cases the returned media type of the result is unpredictable and may differ from one SPARQL endpoint implementation to the other. (Endpoints usually fall back to one of the "meaningful" formats, but it is up to the specific implementation to choose which one that is.) :return: query result :rtype: :class:`QueryResult` instance """ return QueryResult(self._query()) def queryAndConvert(self): """Macro like method: issue a query and return the converted results. :return: the converted query result. See the conversion methods for more details. """ res = self.query() return res.convert() def __str__(self): """This method returns the string representation of a :class:`SPARQLWrapper` object. .. versionadded:: 1.8.3 :return: A human-readable string of the object. :rtype: string """ fullname = self.__module__ + "." + self.__class__.__name__ items = ('"%s" : %r' % (k, v) for k, v in sorted(self.__dict__.items())) str_dict_items = "{%s}" % (',\n'.join(items)) return "<%s object at 0x%016X>\n%s" % (fullname, id(self), str_dict_items) ####################################################################################################### class QueryResult(object): """ Wrapper around an a query result. Users should not create instances of this class, it is generated by a :func:`SPARQLWrapper.query` call. The results can be converted to various formats, or used directly. If used directly: the class gives access to the direct HTTP request results ``response`` obtained from the call to :func:`urllib.urlopen`. It is a file-like object with two additional methods: * ``geturl()`` to return the URL of the resource retrieved * ``info()`` that returns the meta-information of the HTTP result as a dictionary-like object. For convenience, these methods are also available on the :class:`QueryResult` instance. The :func:`__iter__` and :func:`next` methods are also implemented (by mapping them to :attr:`response`). This means that the common idiom ``for l in obj : do_something_with_line(l)`` would work, too. :ivar response: the direct HTTP response; a file-like object, as return by the :func:`urllib2.urlopen` library call. :ivar requestedFormat: The requested format. The possible values are: :data:`JSON`, :data:`XML`, :data:`RDFXML`, :data:`TURTLE`, :data:`N3`, :data:`RDF`, :data:`CSV`, :data:`TSV`, :data:`JSONLD`. :type requestedFormat: string """ def __init__(self, result): """ :param result: HTTP response stemming from a :func:`SPARQLWrapper.query` call, or a tuple with the expected format: (response, format). """ if isinstance(result, tuple): self.response = result[0] self.requestedFormat = result[1] else: self.response = result def geturl(self): """Return the URL of the original call. :return: URL of the original call. :rtype: string """ return self.response.geturl() def info(self): """Return the meta-information of the HTTP result. :return: meta-information of the HTTP result. :rtype: dict """ return KeyCaseInsensitiveDict(self.response.info()) def __iter__(self): """Return an iterator object. This method is expected for the inclusion of the object in a standard ``for`` loop. """ return self.response.__iter__() def next(self): """Method for the standard iterator.""" return self.response.next() def _convertJSON(self): """ Convert a JSON result into a Python dict. This method can be overwritten in a subclass for a different conversion method. :return: converted result. :rtype: dict """ return json.loads(self.response.read().decode("utf-8")) def _convertXML(self): """ Convert an XML result into a Python dom tree. This method can be overwritten in a subclass for a different conversion method. :return: converted result. :rtype: :class:`xml.dom.minidom.Document` """ from xml.dom.minidom import parse return parse(self.response) def _convertRDF(self): """ Convert a RDF/XML result into an RDFLib Graph. This method can be overwritten in a subclass for a different conversion method. :return: converted result. :rtype: :class:`rdflib.graph.Graph` """ try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph retval = ConjunctiveGraph() # (DEPRECATED) this is a strange hack. If the publicID is not set, rdflib (or the underlying xml parser) makes a funny # (DEPRECATED) (and, as far as I could see, meaningless) error message... retval.load(self.response) # (DEPRECATED) publicID=' ') return retval def _convertN3(self): """ Convert a RDF Turtle/N3 result into a string. This method can be overwritten in a subclass for a different conversion method. :return: converted result. :rtype: string """ return self.response.read() def _convertCSV(self): """ Convert a CSV result into a string. This method can be overwritten in a subclass for a different conversion method. :return: converted result. :rtype: string """ return self.response.read() def _convertTSV(self): """ Convert a TSV result into a string. This method can be overwritten in a subclass for a different conversion method. :return: converted result. :rtype: string """ return self.response.read() def _convertJSONLD(self): """ Convert a RDF JSON-LD result into an RDFLib Graph. This method can be overwritten in a subclass for a different conversion method. :return: converted result :rtype: :class:`rdflib.graph.Graph` """ from rdflib import ConjunctiveGraph retval = ConjunctiveGraph() retval.load(self.response, format='json-ld')# (DEPRECATED), publicID=' ') return retval def convert(self): """ Encode the return value depending on the return format: * in the case of :data:`XML`, a DOM top element is returned * in the case of :data:`JSON`, a json conversion will return a dictionary * in the case of :data:`RDF/XML`, the value is converted via RDFLib into a ``RDFLib Graph`` instance * in the case of :data:`JSON-LD`, the value is converted via RDFLib into a ``RDFLib Graph`` instance * in the case of RDF :data:`Turtle`/:data:`N3`, a string is returned * in the case of :data:`CSV`/:data:`TSV`, a string is returned * In all other cases the input simply returned. :return: the converted query result. See the conversion methods for more details. """ def _content_type_in_list(real, expected): """ Internal method for checking if the content-type header received matches any of the content types of the expected list. :param real: The content-type header received. :type real: string :param expected: A list of expected content types. :type expected: list :return: Returns a boolean after checking if the content-type header received matches any of the content types of the expected list. :rtype: boolean """ return True in [real.find(mime) != -1 for mime in expected] def _validate_format(format_name, allowed, mime, requested): """ Internal method for validating if the requested format is one of the allowed formats. :param format_name: The format name (to be used in the warning message). :type format_name: string :param allowed: A list of allowed content types. :type allowed: list :param mime: The content-type header received (to be used in the warning message). :type mime: string :param requested: the requested format. :type requested: string """ if requested not in allowed: message = "Format requested was %s, but %s (%s) has been returned by the endpoint" warnings.warn(message % (requested.upper(), format_name, mime), RuntimeWarning) # TODO. In order to compare properly, the requested QueryType (SPARQL Query Form) is needed. For instance, the unexpected N3 requested for a SELECT would return XML if "content-type" in self.info(): ct = self.info()["content-type"] # returned Content-Type value if _content_type_in_list(ct, _SPARQL_XML): _validate_format("XML", [XML], ct, self.requestedFormat) return self._convertXML() elif _content_type_in_list(ct, _XML): _validate_format("XML", [XML], ct, self.requestedFormat) return self._convertXML() elif _content_type_in_list(ct, _SPARQL_JSON): _validate_format("JSON", [JSON], ct, self.requestedFormat) return self._convertJSON() elif _content_type_in_list(ct, _RDF_XML): _validate_format("RDF/XML", [RDF, XML, RDFXML], ct, self.requestedFormat) return self._convertRDF() elif _content_type_in_list(ct, _RDF_N3): _validate_format("N3", [N3, TURTLE], ct, self.requestedFormat) return self._convertN3() elif _content_type_in_list(ct, _CSV): _validate_format("CSV", [CSV], ct, self.requestedFormat) return self._convertCSV() elif _content_type_in_list(ct, _TSV): _validate_format("TSV", [TSV], ct, self.requestedFormat) return self._convertTSV() elif _content_type_in_list(ct, _RDF_JSONLD): _validate_format("JSON(-LD)", [JSONLD, JSON], ct, self.requestedFormat) return self._convertJSONLD() else: warnings.warn("unknown response content type '%s' returning raw response..." %(ct), RuntimeWarning) return self.response.read() def _get_responseFormat(self): """ Get the response (return) format. The possible values are: :data:`JSON`, :data:`XML`, :data:`RDFXML`, :data:`TURTLE`, :data:`N3`, :data:`CSV`, :data:`TSV`, :data:`JSONLD`. In case there is no Content-Type, ``None`` is return. In all other cases, the raw Content-Type is return. .. versionadded:: 1.8.3 :return: the response format. The possible values are: :data:`JSON`, :data:`XML`, :data:`RDFXML`, :data:`TURTLE`, :data:`N3`, :data:`CSV`, :data:`TSV`, :data:`JSONLD`. :rtype: string """ def _content_type_in_list(real, expected): """ Internal method for checking if the content-type header received matches any of the content types of the expected list. :param real: The content-type header received. :type real: string :param expected: A list of expected content types. :type expected: list :return: Returns a boolean after checking if the content-type header received matches any of the content types of the expected list. :rtype: boolean """ return True in [real.find(mime) != -1 for mime in expected] if "content-type" in self.info(): ct = self.info()["content-type"] # returned Content-Type value if _content_type_in_list(ct, _SPARQL_XML): return XML elif _content_type_in_list(ct, _XML): return XML elif _content_type_in_list(ct, _SPARQL_JSON): return JSON elif _content_type_in_list(ct, _RDF_XML): return RDFXML elif _content_type_in_list(ct, _RDF_TURTLE): return TURTLE elif _content_type_in_list(ct, _RDF_N3): return N3 elif _content_type_in_list(ct, _CSV): return CSV elif _content_type_in_list(ct, _TSV): return TSV elif _content_type_in_list(ct, _RDF_JSONLD): return JSONLD else: warnings.warn("Unknown response content type. Returning raw content-type ('%s')." %(ct), RuntimeWarning) return ct return None def print_results(self, minWidth=None): """This method prints a representation of a :class:`QueryResult` object that MUST has as response format :data:`JSON`. :param minWidth: The minimum width, counting as characters. The default value is ``None``. :type minWidth: string """ # Check if the requested format was JSON. If not, exit. responseFormat = self._get_responseFormat() if responseFormat != JSON: message = "Format return was %s, but JSON was expected. No printing." warnings.warn(message % (responseFormat), RuntimeWarning) return results = self._convertJSON() if minWidth: width = self.__get_results_width(results, minWidth) else: width = self.__get_results_width(results) index = 0 for var in results["head"]["vars"]: print ("?" + var).ljust(width[index]), "|", index += 1 print print "=" * (sum(width) + 3 * len(width)) for result in results["results"]["bindings"]: index = 0 for var in results["head"]["vars"]: result_value = self.__get_prettyprint_string_sparql_var_result(result[var]) print result_value.ljust(width[index]), "|", index += 1 print def __get_results_width(self, results, minWidth=2): width = [] for var in results["head"]["vars"]: width.append(max(minWidth, len(var)+1)) for result in results["results"]["bindings"]: index = 0 for var in results["head"]["vars"]: result_value = self.__get_prettyprint_string_sparql_var_result(result[var]) width[index] = max(width[index], len(result_value)) index += 1 return width def __get_prettyprint_string_sparql_var_result(self, result): value = result["value"] lang = result.get("xml:lang", None) datatype = result.get("datatype", None) if lang is not None: value += "@"+lang if datatype is not None: value += " ["+datatype+"]" return value def __str__(self): """This method returns the string representation of a :class:`QueryResult` object. :return: A human-readable string of the object. :rtype: string .. versionadded:: 1.8.3 """ fullname = self.__module__ + "." + self.__class__.__name__ str_requestedFormat = '"requestedFormat" : '+repr(self.requestedFormat) str_url = self.response.url str_code = self.response.code str_headers = self.response.info() str_response = '"response (a file-like object, as return by the urllib2.urlopen library call)" : {\n\t"url" : "%s",\n\t"code" : "%s",\n\t"headers" : %s}' % (str_url, str_code, str_headers) return "<%s object at 0x%016X>\n{%s,\n%s}" % (fullname, id(self), str_requestedFormat, str_response) sparqlwrapper-1.8.5/SPARQLWrapper/__init__.py000066400000000000000000000024671357765027600211370ustar00rootroot00000000000000# -*- coding: utf8 -*- u""" **SPARQLWrapper** is a simple Python wrapper around a `SPARQL `_ service to remotelly execute your queries. It helps in creating the query invokation and, possibly, convert the result into a more manageable format. """ __version__ = "1.8.5" """The version of SPARQLWrapper""" __authors__ = "Ivan Herman, Sergio Fernández, Carlos Tejo Alonso, Alexey Zakhlestin" """The primary authors of SPARQLWrapper""" __license__ = "W3C® SOFTWARE NOTICE AND LICENSE, http://www.w3.org/Consortium/Legal/copyright-software" """The license governing the use and distribution of SPARQLWrapper""" __url__ = "http://rdflib.github.io/sparqlwrapper" """The URL for SPARQLWrapper's homepage""" __contact__ = "rdflib-dev@googlegroups.com" """Mail list to contact to other people RDFLib and SPARQLWrappers folks and developers""" __date__ = "2019-04-18" """Last update""" __agent__ = "sparqlwrapper %s (rdflib.github.io/sparqlwrapper)" % __version__ from Wrapper import SPARQLWrapper from Wrapper import XML, JSON, TURTLE, N3, JSONLD, RDF, RDFXML, CSV, TSV from Wrapper import GET, POST from Wrapper import SELECT, CONSTRUCT, ASK, DESCRIBE, INSERT, DELETE from Wrapper import URLENCODED, POSTDIRECTLY from Wrapper import BASIC, DIGEST from SmartWrapper import SPARQLWrapper2 sparqlwrapper-1.8.5/custom_fixers/000077500000000000000000000000001357765027600173445ustar00rootroot00000000000000sparqlwrapper-1.8.5/custom_fixers/__init__.py000077500000000000000000000000001357765027600214460ustar00rootroot00000000000000sparqlwrapper-1.8.5/custom_fixers/fix_urllib2.py000077500000000000000000000006431357765027600221450ustar00rootroot00000000000000from lib2to3.fixer_base import BaseFix from lib2to3.fixer_util import Name class FixUrllib2(BaseFix): PATTERN = "power< fixprefix='urllib2' trailer< '.' '_opener' > >|power< fixprefix='urllib2' trailer< '.' '_opener' > trailer< '.' handlers='handlers' > >" def transform(self, node, results): fixprefix = results['fixprefix'] fixprefix.replace(Name('urllib.request', prefix=fixprefix.prefix)) sparqlwrapper-1.8.5/docs/000077500000000000000000000000001357765027600154025ustar00rootroot00000000000000sparqlwrapper-1.8.5/docs/Makefile000066400000000000000000000013621357765027600170440ustar00rootroot00000000000000# Minimal makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build SOURCEDIR = source BUILDDIR = build # Put it first so that "make" without argument is like "make help". help: @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) .PHONY: help Makefile # Catch-all target: route all unknown targets to Sphinx using the new # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). %: Makefile @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) buildapi: sphinx-apidoc -fMe ../SPARQLWrapper/ -o source/ @echo "Auto-generation of SPARQLWrapper documentation finished. " \ "The generated files are in 'source/'" sparqlwrapper-1.8.5/docs/make.bat000066400000000000000000000013641357765027600170130ustar00rootroot00000000000000@ECHO OFF pushd %~dp0 REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set SOURCEDIR=source set BUILDDIR=build if "%1" == "" goto help %SPHINXBUILD% >NUL 2>NUL if errorlevel 9009 ( echo. echo.The 'sphinx-build' command was not found. Make sure you have Sphinx echo.installed, then set the SPHINXBUILD environment variable to point echo.to the full path of the 'sphinx-build' executable. Alternatively you echo.may add the Sphinx directory to PATH. echo. echo.If you don't have Sphinx installed, grab it from echo.http://sphinx-doc.org/ exit /b 1 ) %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% goto end :help %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% :end popd sparqlwrapper-1.8.5/docs/source/000077500000000000000000000000001357765027600167025ustar00rootroot00000000000000sparqlwrapper-1.8.5/docs/source/SPARQLWrapper.KeyCaseInsensitiveDict.rst000066400000000000000000000003071357765027600263470ustar00rootroot00000000000000SPARQLWrapper.KeyCaseInsensitiveDict module =========================================== .. automodule:: SPARQLWrapper.KeyCaseInsensitiveDict :members: :undoc-members: :show-inheritance: sparqlwrapper-1.8.5/docs/source/SPARQLWrapper.SPARQLExceptions.rst000066400000000000000000000001741357765027600250440ustar00rootroot00000000000000SPARQLWrapper.SPARQLExceptions module ===================================== .. automodule:: SPARQLWrapper.SPARQLExceptions sparqlwrapper-1.8.5/docs/source/SPARQLWrapper.SmartWrapper.rst000066400000000000000000000002201357765027600244170ustar00rootroot00000000000000SPARQLWrapper.SmartWrapper module ================================= .. automodule:: SPARQLWrapper.SmartWrapper :member-order: alphabetical sparqlwrapper-1.8.5/docs/source/SPARQLWrapper.Wrapper.rst000066400000000000000000000001731357765027600234170ustar00rootroot00000000000000SPARQLWrapper.Wrapper module ============================ .. automodule:: SPARQLWrapper.Wrapper :no-show-inheritance: sparqlwrapper-1.8.5/docs/source/_templates/000077500000000000000000000000001357765027600210375ustar00rootroot00000000000000sparqlwrapper-1.8.5/docs/source/_templates/globaltocindex.html000066400000000000000000000004451357765027600247260ustar00rootroot00000000000000{# basic/globaltoc.html ~~~~~~~~~~~~~~~~~~~~ Sphinx sidebar template: global table of contents. :copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. Modified to work properly with the index page #} {{ toctree() }} sparqlwrapper-1.8.5/docs/source/_templates/localtocindex.html000066400000000000000000000006141357765027600245560ustar00rootroot00000000000000{# basic/localtoc.html ~~~~~~~~~~~~~~~~~~~ Sphinx sidebar template: local table of contents. :copyright: Copyright 2007-2017 by the Sphinx team, see AUTHORS. :license: BSD, see LICENSE for details. Modified to work properly with the index page #} {%- if display_toc %}

{{ _('Table Of Contents') }}

{{ toc }} {%- endif %} sparqlwrapper-1.8.5/docs/source/_templates/sidebarhelp.html000066400000000000000000000002541357765027600242100ustar00rootroot00000000000000

Need help?

Open an issue in our issue tracker. Issues that are just questions are fine.

sparqlwrapper-1.8.5/docs/source/changelog.rst000066400000000000000000000000431357765027600213600ustar00rootroot00000000000000 .. include:: ../../ChangeLog.txt sparqlwrapper-1.8.5/docs/source/conf.py000066400000000000000000000154021357765027600202030ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/master/config # -- Path setup -------------------------------------------------------------- # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # import os import sys sys.path.insert(0, os.path.abspath('../..')) sys.path.insert(0, os.path.abspath('../../SPARQLWrapper')) # from https://stackoverflow.com/questions/10324393/sphinx-build-fail-autodoc-cant-import-find-module from SPARQLWrapper import __version__ # -- Project information ----------------------------------------------------- project = u'SPARQLWrapper' copyright = u'2019, `W3C® SOFTWARE NOTICE AND LICENSE `_' author = u'Ivan Herman' author = u'Sergio Fernández' author = u'Carlos Tejo Alonso' author = u'Alexey Zakhlestin' # The short X.Y version version = __version__ # The full version, including alpha/beta/rc tags #release = u'1.8.5.dev0' # -- General configuration --------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.viewcode', 'sphinx.ext.githubpages', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The master toctree document. master_doc = 'index' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This pattern also affects html_static_path and html_extra_path. exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = None autodoc_member_order = 'bysource' autodoc_default_options = { 'members': None, 'private-members': None, 'show-inheritance': None, 'special-members': '__init__' } autoclass_content = 'class' #autosummary_generate = True # -- Options for HTML output ------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = { # Toc options 'collapse_navigation': False, 'sticky_navigation': True, 'navigation_depth': 4, 'includehidden': True, 'titles_only': False } # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". #html_static_path = ['_static'] # Custom sidebar templates, must be a dictionary that maps document names # to template names. # # The default sidebars (for documents that don't match any pattern) are # defined by theme itself. Builtin themes are using these templates by # default: ``['localtoc.html', 'relations.html', 'sourcelink.html', # 'searchbox.html']``. # # html_sidebars = { # '**': ['globaltoc.html', 'sidebarhelp.html', # 'searchbox.html'], # 'index': ['localtocindex.html', 'globaltocindex.html', 'sidebarhelp.html', # 'searchbox.html'], # } # -- Options for HTMLHelp output --------------------------------------------- # Output file base name for HTML help builder. htmlhelp_basename = 'SPARQLWrapperdoc' html_show_copyright = False html_show_sphinx = False # -- Options for LaTeX output ------------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'SPARQLWrapper.tex', u'SPARQLWrapper Documentation', u'CHANGE\\_AUTHORS', 'manual'), ] # -- Options for manual page output ------------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'sparqlwrapper', u'SPARQLWrapper Documentation', [author], 1) ] # -- Options for Texinfo output ---------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'SPARQLWrapper', u'SPARQLWrapper Documentation', author, 'SPARQLWrapper', 'One line description of project.', 'Miscellaneous'), ] # -- Options for Epub output ------------------------------------------------- # Bibliographic Dublin Core info. epub_title = project # The unique identifier of the text. This can be a ISBN number # or the project homepage. # # epub_identifier = '' # A unique identification for the text. # # epub_uid = '' # A list of files that should not be packed into the epub file. epub_exclude_files = ['search.html'] # -- Extension configuration ------------------------------------------------- # -- Options for intersphinx extension --------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { 'https://docs.python.org/2/': None, } # -- Options for todo extension ---------------------------------------------- # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True sparqlwrapper-1.8.5/docs/source/index.rst000066400000000000000000000016371357765027600205520ustar00rootroot00000000000000======================================= SPARQL Endpoint interface to Python ======================================= |Build Status| |PyPi version| **SPARQLWrapper** is a simple Python wrapper around a `SPARQL `_ service to remotelly execute your queries. It helps in creating the query invokation and, possibly, convert the result into a more manageable format. .. toctree:: :hidden: :caption: Basic steps main .. toctree:: :hidden: :caption: Python Package modules ChangeLog Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` .. |Build Status| image:: https://secure.travis-ci.org/RDFLib/sparqlwrapper.svg?branch=master :target: https://travis-ci.org/RDFLib/sparqlwrapper .. |PyPi version| image:: https://badge.fury.io/py/SPARQLWrapper.svg :target: https://pypi.python.org/pypi/SPARQLWrappersparqlwrapper-1.8.5/docs/source/main.rst000066400000000000000000000000401357765027600203520ustar00rootroot00000000000000 .. include:: ../../README.rst sparqlwrapper-1.8.5/docs/source/modules.rst000066400000000000000000000002751357765027600211100ustar00rootroot00000000000000SPARQLWrapper package ===================== .. toctree:: SPARQLWrapper.Wrapper SPARQLWrapper.SmartWrapper SPARQLWrapper.SPARQLExceptions SPARQLWrapper.KeyCaseInsensitiveDict sparqlwrapper-1.8.5/ez_setup.py000066400000000000000000000240551357765027600166700ustar00rootroot00000000000000#!python """Bootstrap setuptools installation If you want to use setuptools in your package's setup.py, just include this file in the same directory with it, and add this to the top of your setup.py:: from ez_setup import use_setuptools use_setuptools() If you want to require a specific version of setuptools, set a download mirror, or use an alternate download directory, you can do so by supplying the appropriate options to ``use_setuptools()``. This file can also be run as a script to install or upgrade setuptools. """ import sys DEFAULT_VERSION = "0.6c11" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', 'setuptools-0.6c10-py2.3.egg': 'ce1e2ab5d3a0256456d9fc13800a7090', 'setuptools-0.6c10-py2.4.egg': '57d6d9d6e9b80772c59a53a8433a5dd4', 'setuptools-0.6c10-py2.5.egg': 'de46ac8b1c97c895572e5e8596aeb8c7', 'setuptools-0.6c10-py2.6.egg': '58ea40aef06da02ce641495523a0b7f5', 'setuptools-0.6c11-py2.3.egg': '2baeac6e13d414a9d28e7ba5b5a596de', 'setuptools-0.6c11-py2.4.egg': 'bd639f9b0eac4c42497034dec2ec0c2b', 'setuptools-0.6c11-py2.5.egg': '64c94f3bf7a72a13ec83e0b24f2749b2', 'setuptools-0.6c11-py2.6.egg': 'bfa92100bd772d5a213eedd356d64086', 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', } import sys, os try: from hashlib import md5 except ImportError: from md5 import md5 def _validate_md5(egg_name, data): if egg_name in md5_data: digest = md5(data).hexdigest() if digest != md5_data[egg_name]: print >>sys.stderr, ( "md5 validation of %s failed! (Possible download problem?)" % egg_name ) sys.exit(2) return data def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download() except pkg_resources.DistributionNotFound: return do_download() def download_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 ): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log if delay: log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version %s to run (even to display help). I will attempt to download it for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""", version, download_base, delay, url ); from time import sleep; sleep(delay) log.warn("Downloading %s", url) src = urllib2.urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = _validate_md5(egg_name, src.read()) dst = open(saveto,"wb"); dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" try: import setuptools except ImportError: egg = None try: egg = download_setuptools(version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) else: if setuptools.__version__ == '0.0.1': print >>sys.stderr, ( "You have an obsolete version of setuptools installed. Please\n" "remove it from your system entirely before rerunning this script." ) sys.exit(2) req = "setuptools>="+version import pkg_resources try: pkg_resources.require(req) except pkg_resources.VersionConflict: try: from setuptools.command.easy_install import main except ImportError: from easy_install import main main(list(argv)+[download_setuptools(delay=0)]) sys.exit(0) # try to force an exit else: if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close() if __name__=='__main__': if len(sys.argv)>2 and sys.argv[1]=='--md5update': update_md5(sys.argv[2:]) else: main(sys.argv[1:]) sparqlwrapper-1.8.5/requirements.development.txt000066400000000000000000000000471357765027600222600ustar00rootroot00000000000000nose>=1.3.7 2to3>=1.0 setuptools>=3.7.1sparqlwrapper-1.8.5/requirements.txt000066400000000000000000000000141357765027600177310ustar00rootroot00000000000000rdflib>=4.0 sparqlwrapper-1.8.5/run_tests_py3.sh000077500000000000000000000023311357765027600176310ustar00rootroot00000000000000#!/bin/bash # FOR MANUAL RUNNING, IT REQUIRES modules: 2to3, python3-setuptools, python3-nose # REMEMBER to remove PYTHON_VERSION SUFFIX # Please, install the required tools previously: # $ sudo apt-get install 2to3 # $ sudo apt-get install python3-setuptools # $ sudo apt-get install python3-nose function cmdcheck() { command -v $1 >/dev/null 2>&1 || { echo >&2 "ERROR: command $1 required but it's not installed; aborting..."; exit -1; } } cmdcheck python3 PYTHON_VERSION=`python3 -c "import sys;t='{v[0]}.{v[1]}'.format(v=list(sys.version_info[:2]));sys.stdout.write(t)";` #cmdcheck 2to3-$PYTHON_VERSION #cmdcheck nosetests-$PYTHON_VERSION #cmdcheck nosetests3 python3 setup.py build if [ -d build/py3_testing ]; then rm -r build/py3_testing echo "removed build/py3_testing directory from previous run" fi mkdir build/py3_testing cp -r test build/py3_testing/ cp -r build/lib/SPARQLWrapper build/py3_testing/ cd build/py3_testing if command -v 2to3-$PYTHON_VERSION; then 2to3-$PYTHON_VERSION -wn --no-diffs test else 2to3 -wn --no-diffs test fi sed -i.bak s/urllib2._opener/urllib.request._opener/g test/wrapper_test.py if hash nosetests3 2>/dev/null; then nosetests3 else nosetests fi cd ../.. sparqlwrapper-1.8.5/scripts/000077500000000000000000000000001357765027600161415ustar00rootroot00000000000000sparqlwrapper-1.8.5/scripts/example-ask.py000066400000000000000000000014041357765027600207210ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- from SPARQLWrapper import SPARQLWrapper, JSON, XML, CSV, TSV sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" ASK WHERE { rdfs:label "Asturias"@es } """) # JSON example print '\n\n*** JSON Example' sparql.setReturnFormat(JSON) results = sparql.query().convert() print results # XML example print '\n\n*** XML Example' sparql.setReturnFormat(XML) results = sparql.query().convert() print results.toxml() # CSV example print '\n\n*** CSV Example' sparql.setReturnFormat(CSV) results = sparql.query().convert() print results # TSV example print '\n\n*** TSV Example' sparql.setReturnFormat(TSV) results = sparql.query().convert() print results sparqlwrapper-1.8.5/scripts/example-construct.py000066400000000000000000000023501357765027600221700ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- from SPARQLWrapper import SPARQLWrapper, XML, N3, TURTLE, JSONLD from rdflib import Graph sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX dbo: PREFIX schema: CONSTRUCT { ?lang a schema:Language ; schema:alternateName ?iso6391Code . } WHERE { ?lang a dbo:Language ; dbo:iso6391Code ?iso6391Code . FILTER (STRLEN(?iso6391Code)=2) # to filter out non-valid values } """) # RDF/XML example print '\n\n*** RDF/XML Example' sparql.setReturnFormat(XML) results = sparql.query().convert() print(results.serialize(format='xml')) # N3 example print '\n\n*** N3 Example' sparql.setReturnFormat(N3) results = sparql.query().convert() g = Graph() g.parse(data=results, format="n3") print(g.serialize(format='n3')) # Turtle example print '\n\n*** TURTLE Example' sparql.setReturnFormat(TURTLE) results = sparql.query().convert() g = Graph() g.parse(data=results, format="turtle") print(g.serialize(format='turtle')) # JSONLD example print '\n\n*** JSONLD Example' sparql.setReturnFormat(JSONLD) results = sparql.query().convert() print(results.serialize(format='json-ld')) sparqlwrapper-1.8.5/scripts/example-dbpedia.py000066400000000000000000000014061357765027600215350ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- from SPARQLWrapper import SPARQLWrapper, JSON sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX rdfs: SELECT ?label WHERE { rdfs:label ?label } """) sparql.setReturnFormat(JSON) results = sparql.query() results.print_results() print sparql.setQuery(""" PREFIX rdfs: PREFIX dbp: SELECT ?cheese ?label WHERE { ?cheese a ; dbp:region ; rdfs:label ?label . } """) sparql.setReturnFormat(JSON) results = sparql.query() results.print_results() sparqlwrapper-1.8.5/scripts/example-delete.py000066400000000000000000000006101357765027600214030ustar00rootroot00000000000000from SPARQLWrapper import SPARQLWrapper, POST, DIGEST sparql = SPARQLWrapper("https://example.org/sparql-auth") sparql.setHTTPAuth(DIGEST) sparql.setCredentials("login", "password") sparql.setMethod(POST) sparql.setQuery(""" WITH DELETE { rdfs:label "Asturies"@ast } """) results = sparql.query() print results.response.read()sparqlwrapper-1.8.5/scripts/example-describe.py000066400000000000000000000016321357765027600217260ustar00rootroot00000000000000from SPARQLWrapper import SPARQLWrapper, RDFXML, N3, TURTLE, JSONLD from rdflib import Graph sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" DESCRIBE """) # RDF/XML example print '\n\n*** RDF/XML Example' sparql.setReturnFormat(RDFXML) results = sparql.query().convert() print(results.serialize(format='xml')) # N3 example print '\n\n*** N3 Example' sparql.setReturnFormat(N3) results = sparql.query().convert() g = Graph() g.parse(data=results, format="n3") print(g.serialize(format='n3')) # Turtle example print '\n\n*** TURTLE Example' sparql.setReturnFormat(TURTLE) results = sparql.query().convert() g = Graph() g.parse(data=results, format="turtle") print(g.serialize(format='turtle')) # JSONLD example print '\n\n*** JSONLD Example' sparql.setReturnFormat(JSONLD) results = sparql.query().convert() print(results.serialize(format='json-ld')) sparqlwrapper-1.8.5/scripts/example-federated.py000066400000000000000000000014721357765027600220730ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- from SPARQLWrapper import SPARQLWrapper, JSON sparql = SPARQLWrapper("http://agrovoc.uniroma2.it:3030/agrovoc/sparql") query = """ PREFIX skos: PREFIX rdf: SELECT ?conceptAGROVOC ?conceptGEMET ?label WHERE { ?conceptAGROVOC rdf:type skos:Concept ; skos:prefLabel ?label; skos:inScheme . FILTER (lang(?label) = 'en') SERVICE { ?conceptGEMET skos:prefLabel ?label ; skos:inScheme . } } """ sparql.setQuery(query) sparql.setReturnFormat(JSON) results = sparql.query().print_results() sparqlwrapper-1.8.5/scripts/example-insert-using-rdflib.py000066400000000000000000000017431357765027600240400ustar00rootroot00000000000000from rdflib import Graph, URIRef, Literal from rdflib.namespace import RDFS g = Graph() asturias = URIRef("http://dbpedia.org/resource/Asturias") g.add( (asturias, RDFS.label, Literal('Asturies', lang="ast") ) ) g.add( (asturias, RDFS.label, Literal('Asturias', lang="es") ) ) g.add( (asturias, RDFS.label, Literal('Asturien', lang="de") ) ) ############################################################################### triples = "" for subject,predicate,obj in g: triples = triples + subject.n3() + " " + predicate.n3() + " " + obj.n3() + " . \n" query = """WITH INSERT {"""+ triples + """}""" ############################################################################### from SPARQLWrapper import SPARQLWrapper, POST, DIGEST sparql = SPARQLWrapper("https://example.org/sparql-auth") sparql.setHTTPAuth(DIGEST) sparql.setCredentials("login", "password") sparql.setMethod(POST) sparql.setQuery(query) results = sparql.query() print results.response.read() sparqlwrapper-1.8.5/scripts/example-insert.py000066400000000000000000000006111357765027600214460ustar00rootroot00000000000000from SPARQLWrapper import SPARQLWrapper, POST, DIGEST sparql = SPARQLWrapper("https://example.org/sparql-auth") sparql.setHTTPAuth(DIGEST) sparql.setCredentials("login", "password") sparql.setMethod(POST) sparql.setQuery(""" WITH INSERT { rdfs:label "Asturies"@ast } """) results = sparql.query() print results.response.read() sparqlwrapper-1.8.5/scripts/example-optional.py000066400000000000000000000013621357765027600217730ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- from SPARQLWrapper import SPARQLWrapper, JSON sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX rdfs: SELECT ?person ?party WHERE { ?person OPTIONAL { ?person ?party } } """) # JSON example print '\n\n*** JSON Example' sparql.setReturnFormat(JSON) results = sparql.query().convert() for result in results["results"]["bindings"]: if result.has_key("party"): print "* " + result["person"]["value"] + " ** " + result["party"]["value"] else: print result["person"]["value"] sparqlwrapper-1.8.5/scripts/example.py000066400000000000000000000021701357765027600201460ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- from SPARQLWrapper import SPARQLWrapper, JSON, XML, N3, RDF, CSV, TSV sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX rdfs: SELECT ?label WHERE { rdfs:label ?label } """) # JSON example print '\n\n*** JSON Example' sparql.setReturnFormat(JSON) results = sparql.query().convert() for result in results["results"]["bindings"]: print result["label"]["value"] # XML example print '\n\n*** XML Example' sparql.setReturnFormat(XML) results = sparql.query().convert() print results.toxml() # N3 example print '\n\n*** N3 Example' sparql.setReturnFormat(N3) results = sparql.query().convert() print results # RDF example print '\n\n*** RDF Example' sparql.setReturnFormat(RDF) results = sparql.query().convert() print results.serialize() # CSV example print '\n\n*** CSV Example' sparql.setReturnFormat(CSV) results = sparql.query().convert() print results # TSV example print '\n\n*** TSV Example' sparql.setReturnFormat(TSV) results = sparql.query().convert() print results sparqlwrapper-1.8.5/scripts/sparql.py000077500000000000000000000043161357765027600200240ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- import sys import getopt from SPARQLWrapper import SPARQLWrapper2 localSparqler = "http://localhost:2020/sparql" localVirtuoso = "http://localhost:8890/sparql" def main(server, query, sponge=False): sparql = SPARQLWrapper2(server) if sponge: sparql.addExtraURITag("should-sponge", "grab-everything") sparql.setQuery(query) res = sparql.query() variables = res.variables print "Variables:" print variables print print "Bindings:" for b in res.bindings: for v in res.variables: try: val = b[v] if val.lang: str = "%s: %s@%s" % (v, val.value, val.lang) elif val.datatype: str = "%s: %s^^%s" % (v, val.value, val.datatype) else: str = "%s: %s" % (v, val.value) except KeyError: # no binding to that one... str = "%s: <>" % v print str.encode('utf-8') print # ------------------------------------------------------------------------------------------------------------- server = localSparqler query = "" sponge = False usagetxt = """%s [-s] [-u url] [file] -s: use local sparqler (default) -v: use local virtuoso -u url: server url -p: issue an extra sponge for virtuoso file: sparql query file """ def usage(): print usagetxt % sys.argv[0] sys.exit(1) if __name__ == '__main__': if len(sys.argv) == 1: usage() try: opts, args = getopt.getopt(sys.argv[1:], "shu:pv") for o, a in opts: if o == "-s": server = localSparqler elif o == "-v": server = localVirtuoso sponge = True elif o == "-h": print usage sys.exit(0) elif o == "-u": server = a elif o == "-p": sponge = True if query == "" and len(args) > 0: inp = file(args[0]) query = "" for l in inp: query += l except: usage() if query == "": usage() main(server, query, sponge) sparqlwrapper-1.8.5/setup.py000077500000000000000000000053261357765027600161750ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import sys try: from ez_setup import use_setuptools use_setuptools() except: pass from setuptools import setup try: import six py3 = six.PY3 except: py3 = sys.version_info[0] >= 3 # metadata import re _version_re = re.compile(r'__version__\s*=\s*"(.*)"') _authors_re = re.compile(r'__authors__\s*=\s*"(.*)"') _url_re = re.compile(r'__url__\s*=\s*"(.*)"') for line in open('SPARQLWrapper/__init__.py'): version_match = _version_re.match(line) if version_match: version = version_match.group(1) authors_match = _authors_re.match(line) if authors_match: authors = authors_match.group(1) url_match = _url_re.match(line) if url_match: url = url_match.group(1) # requirements with open('requirements.txt', 'r') as f: _install_requires = [line.rstrip('\n') for line in f] setup( name = 'SPARQLWrapper', version = version, description = 'SPARQL Endpoint interface to Python', long_description = 'This is a wrapper around a SPARQL service. It helps in creating the query URI and, possibly, convert the result into a more manageable format.', license = 'W3C SOFTWARE NOTICE AND LICENSE', author = authors, url = url, download_url = 'https://github.com/RDFLib/sparqlwrapper/releases', platforms = ['any'], packages = ['SPARQLWrapper'], install_requires = _install_requires, extras_require = { 'keepalive': ['keepalive>=0.5'], }, classifiers = [ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: W3C License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', 'Topic :: Software Development :: Libraries :: Python Modules', ], keywords = ['python', 'sparql', 'rdf', 'rdflib'], use_2to3 = True, use_2to3_fixers = ['custom_fixers'], project_urls={ 'Home': 'https://rdflib.github.io/sparqlwrapper/', 'Documentation': 'https://rdflib.github.io/sparqlwrapper/doc/', 'Source': 'https://github.com/RDFLib/sparqlwrapper', 'Tracker': 'https://github.com/RDFLib/sparqlwrapper/issues', } ) sparqlwrapper-1.8.5/test/000077500000000000000000000000001357765027600154315ustar00rootroot00000000000000sparqlwrapper-1.8.5/test/4store__v1_1_5__agroportal__test.py000066400000000000000000001676651357765027600242500ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "http://sparql.agroportal.lirmm.fr/sparql/" # 4store SPARQL server v1.1.5-122-g1788d29 prefixes = """ PREFIX rdf: PREFIX rdfs: PREFIX skos: """ selectQuery = """ SELECT DISTINCT ?s WHERE { ?s a ?o . VALUES ?o {} } LIMIT 100 """ selectQueryCSV_TSV = """ SELECT DISTINCT ?s ?o WHERE { ?s a ?o . VALUES ?o {} } LIMIT 100 """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v skos:prefLabel ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { skos:prefLabel ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # 4store uses URL parameters or conneg. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("4store does not support receiving unexpected output values (check Wrapper code for TSV URL generation)") def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("4store does not support receiving unexpected output values (n3 is not a valid alias)") def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("4store does not support receiving unexpected output values (json-ld is not a valid alias)") def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV is supported for 4store, but it returns a text/plain instead of text/tab-separated-values") def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip("4store does not support receiving unexpected output values (n3 is not a valid alias)") def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("4store does not support receiving unexpected output values (json-ld is not a valid alias)") def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unknown return format for ASK queryType (XML is sent) # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("4store does not support receiving unexpected output values (rdf+xml is not a valid alias)") def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias ('text' is the one used) @unittest.skip("4store does not support receiving unexpected output values (turtle is not a valid alias)") def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias ('text' is the one used) # Working with Content Negotiation def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias ('text' is the one used) # But it returns text/turtle def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias ('text' is the one used) # Working with Content Negotiation def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("4store does not support receiving unexpected output values (n3 is not a valid alias)") def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # Returns text/turtle def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # Returns text/turtle def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("JSON-LD is not currently supported") def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not currently supported") def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not currently supported") def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not currently supported") def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml @unittest.skip("4store returns text/turtle instead of the expected default application/rdf+xml") def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml @unittest.skip("4store returns text/turtle instead of the expected default application/rdf+xml") def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("4store does not support receiving unexpected output values (rdf+xml is not a valid alias)") def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias ('text' is the one used) @unittest.skip("4store does not support receiving unexpected output values (turtle is not a valid alias)") def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias ('text' is the one used) def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias ('text' is the one used) def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias ('text' is the one used) def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("4store does not support receiving unexpected output values (n3 is not a valid alias)") def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # Returns text/turtle def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # Returns text/turtle def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("JSON-LD is not currently supported") def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not currently supported") def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not currently supported") def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not currently supported") def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml @unittest.skip("4store returns text/csv instead of the expected default application/rdf+xml. AND the content of the response is a Turtle document. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml @unittest.skip("4store returns application/sparql-results+json instead of the expected default application/rdf+xml. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() @unittest.skip('Store 4. parser error: Failed to decode SPARQL ID "dbpedia:Victoria\". See #94') def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip('Store 4. parser error: Failed to decode SPARQL ID "dbpedia:Category\". See #94') def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, POST) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/agrovoc-allegrograph_on_hold.py000066400000000000000000000723411357765027600236210ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "http://202.45.139.84:10035/catalogs/fao/repositories/agrovoc" prefixes = """ PREFIX rdf: PREFIX rdfs: PREFIX skos: """ selectQuery = """ SELECT ?label WHERE { skos:prefLabel ?label . } """ selectQueryCSV_TSV = """ SELECT ?label ?created WHERE { skos:prefLabel ?label ; ?created } """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v skos:prefLabel ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { skos:prefLabel ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=True): # Allegrograph uses only content negotiation (no URL parameters). sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # asking for an unexpected return format for SELECT queryType def testSelectByGETinN3(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unexpected return format for SELECT queryType def testSelectByPOSTinN3(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unexpected return format for SELECT queryType def testSelectByGETinJSONLD(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unexpected return format for SELECT queryType def testSelectByPOSTinJSONLD(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("CSV (text/csv) is not supported currently for AllegroGraph for ASK query type") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() @unittest.skip("CSV (text/csv) is not supported currently for AllegroGraph for ASK query type") def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() @unittest.skip("TSV (text/tab-separated-values) is not supported currently for AllegroGraph for ASK query type") def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() @unittest.skip("TSV (text/tab-separated-values) is not supported currently for AllegroGraph for ASK query type") def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # asking for an unexpected return format for ASK queryType def testAskByGETinN3(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unexpected return format for ASK queryType def testAskByPOSTinN3(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unexpected return format for ASK queryType def testAskByGETinJSONLD(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unexpected return format for ASK queryType def testAskByPOSTinJSONLD(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() results.toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # JSON-LD is not supported currently for AllegroGraph @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # JSON-LD is not supported currently for AllegroGraph @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unexpected return format for CONSTRUCT queryType def testConstructByGETinJSON(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unexpected return format for CONSTRUCT queryType def testConstructByPOSTinJSON(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unexpected return format for CONSTRUCT queryType. For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinCSV(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unexpected return format for CONSTRUCT queryType. For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinCSV(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # JSON-LD is not supported currently for AllegroGraph @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # JSON-LD is not supported currently for AllegroGraph @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unexpected return format for DESCRIBE queryType def testDescribeByGETinJSON(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unexpected return format for DESCRIBE queryType def testDescribeByPOSTinJSON(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unexpected return format for DESCRIBE queryType. For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinCSV(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unexpected return format for DESCRIBE queryType. For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinCSV(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() @unittest.skip("Allegrograph returns Value \"\\\" not recognized Error. See #94") def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip("Allegrograph returns Value \"\\\" not recognized Error. See #94") def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, POST) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/allegrograph__v4_14_1__mmi__test.py000066400000000000000000001635431357765027600241610ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "https://mmisw.org/sparql" # 4.14.1 http://mmisw.org:10035/doc/release-notes.html # AllegroServe/1.3.28 prefixes = """ PREFIX rdf: PREFIX rdfs: PREFIX skos: PREFIX ioosCat: PREFIX ioosPlat: """ selectQuery = """ SELECT ?p WHERE { ?p a ioosCat:Category } ORDER BY ?p """ selectQueryCSV_TSV = """ SELECT DISTINCT ?cat ?platform ?definition WHERE { ?platform a ioosPlat:Platform . ?platform ioosPlat:Definition ?definition . ?cat skos:narrowMatch ?platform . } ORDER BY ?cat ?platform """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v skos:prefLabel ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { rdfs:label ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT * WHERE { ?subject ?predicate ?object . } LIMIT 10 """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # AllegroGraph uses URL parameters or content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("CSV (text/csv) is not supported currently for AllegroGraph for ASK query type") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("CSV (text/csv) is not supported currently for AllegroGraph for ASK query type") def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("CSV (text/csv) is not supported currently for AllegroGraph for ASK query type") def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("CSV (text/csv) is not supported currently for AllegroGraph for ASK query type") def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV (text/tab-separated-values) is not supported currently for AllegroGraph for ASK query type") def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV (text/tab-separated-values) is not supported currently for AllegroGraph for ASK query type") def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV (text/tab-separated-values) is not supported currently for AllegroGraph for ASK query type") def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV (text/tab-separated-values) is not supported currently for AllegroGraph for ASK query type") def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Turtle is not supported currently for AllegroGraph") def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Turtle is not supported currently for AllegroGraph") def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Turtle is not supported currently for AllegroGraph") def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Turtle is not supported currently for AllegroGraph") def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Turtle is not supported currently for AllegroGraph") def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Turtle is not supported currently for AllegroGraph") def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Turtle is not supported currently for AllegroGraph") def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Turtle is not supported currently for AllegroGraph") def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("JSON-LD is not supported currently for AllegroGraph") def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml # Returned application/rdf+xml def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() @unittest.skip("Allegrograph returns Value \"\\\" not recognized Error. See #94") def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip("Allegrograph returns Value \"\\\" not recognized Error. See #94") def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, POST) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/blazegraph__wikidata__test.py000066400000000000000000001713641357765027600233500ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import time import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "https://query.wikidata.org/sparql" prefixes = """ PREFIX rdf: PREFIX rdfs: PREFIX skos: PREFIX entity: """ selectQuery = """ SELECT ?predicate ?object WHERE { entity:Q3934 ?predicate ?object . } LIMIT 10 """ selectQueryCSV_TSV = """ SELECT ?predicate ?object WHERE { entity:Q3934 ?predicate ?object . } LIMIT 10 """ askQuery = """ ASK { rdfs:label "Asturias"@es } """ constructQuery = """ CONSTRUCT { _:v skos:prefLabel ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { rdfs:label ?label . FILTER langMatches( lang(?label), "es" ) } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: PREFIX rdfs: PREFIX skos: PREFIX entity: SELECT ?predicate ?object WHERE { entity:Q3934 ?predicate ?object . } LIMIT 10 """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?predicate ?object WHERE { entity:Q3934 ?predicate ?object . } LIMIT 10 """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # Blazegraph uses URL parameters or content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: time.sleep(2.5) # sleeps for 2.5 seconds, in order to avoid disruptions in the server result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. csv is not a valid alias. Use content negotiation instead") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. csv is not a valid alias. Use content negotiation instead") def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. tsv is not a valid alias. Use content negotiation instead") def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. tsv is not a valid alias. Use content negotiation instead") def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("CSV is not supported for ASK queries in Blazegraph") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("CSV is not supported for ASK queries in Blazegraph") def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("CSV is not supported for ASK queries in Blazegraph") def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("CSV is not supported for ASK queries in Blazegraph") def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV is not supported for ASK queries in Blazegraph") def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV is not supported for ASK queries in Blazegraph") def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV is not supported for ASK queries in Blazegraph") def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("TSV is not supported for ASK queries in Blazegraph") def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. turtle is not a valid alias. Use content negotiation instead") def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. turtle is not a valid alias. Use content negotiation instead") def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. n3 is not a valid alias. Use content negotiation instead") def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. n3 is not a valid alias. Use content negotiation instead") def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # json-ld is not a valid alias. Use content negotiation instead @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. json-ld is not a valid alias. Use content negotiation instead") def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. json-ld is not a valid alias. Use content negotiation instead") def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json is valid alias but returns application/sparql-results+json @unittest.skip("Blazegraph returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json is valid alias but returns application/sparql-results+json @unittest.skip("Blazegraph returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. turtle is not a valid alias. Use content negotiation instead") def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. turtle is not a valid alias. Use content negotiation instead") def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. n3 is not a valid alias. Use content negotiation instead") def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. n3 is not a valid alias. Use content negotiation instead") def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. json-ld is not a valid alias. Use content negotiation instead") def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Blazegraph does not support receiving unexpected 'format' values. json-ld is not a valid alias. Use content negotiation instead") def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml # Returned application/rdf+xml def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json is valid alias but returns application/sparql-results+json @unittest.skip("Blazegraph returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json is valid alias but returns application/sparql-results+json @unittest.skip("Blazegraph returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is application/rdf+xml def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) @unittest.skip('Blazegraph. org.openrdf.query.MalformedQueryException: Multiple prefix declarations for prefix xxx') def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip('Blazegraph. parser error: Failed to decode SPARQL ID "dbpedia:Category\". See #94') def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, POST) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/fuseki2__v3_6_0__agrovoc__test.py000066400000000000000000001602021357765027600236440ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "http://agrovoc.uniroma2.it:3030/agrovoc/sparql" # Fuseki 3.6.0 (Fuseki2) prefixes = """ PREFIX rdf: PREFIX rdfs: PREFIX skos: """ selectQuery = """ SELECT ?label WHERE { skos:prefLabel ?label . } """ selectQueryCSV_TSV = """ SELECT ?label ?created WHERE { skos:prefLabel ?label ; ?created } """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v skos:prefLabel ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { skos:prefLabel ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # Fuseki uses URL parameters OR content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: n3") def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: n3") def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: json-ld") def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: json-ld") def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: n3") def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: n3") def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: json-ld") def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: json-ld") def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: rdf+xml") def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: rdf+xml") def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: turtle") def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: turtle") def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: n3") def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: n3") def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # json-ld is not a valid alias. Use content negotiation instead def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("fuseki2: Can't determine output content type: csv") def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("fuseki2: Can't determine output content type: csv") def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # DIFFERENT: json is an alias of json-ld def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # DIFFERENT: json is an alias of json-ld def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: rdf+xml") def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: rdf+xml") def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: turtle") def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: turtle") def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: n3") def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: n3") def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("fuseki2: Can't determine output content type: csv") def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("fuseki2: Can't determine output content type: csv") def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # DIFFERENT: json is an alias of json-ld def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # DIFFERENT: json is an alias of json-ld def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip('Fuseki Lexical error at line 8, column 45. Encountered: ":" (58), after : "\\". See #94') def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, POST) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/fuseki2__v3_8_0__stw__test.py000066400000000000000000001602651357765027600230340ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import time import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "http://zbw.eu/beta/sparql/stw/query" # Fuseki 3.8.0 (Fuseki2) prefixes = """ PREFIX rdf: PREFIX rdfs: PREFIX skos: """ selectQuery = """ SELECT ?label WHERE { skos:prefLabel ?label . } """ selectQueryCSV_TSV = """ SELECT ?label ?inScheme WHERE { skos:prefLabel ?label ; skos:inScheme ?inScheme } """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v skos:prefLabel ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { skos:prefLabel ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # Fuseki uses URL parameters OR content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: time.sleep(2.5) # sleeps for 2.5 seconds, in order to avoid disruptions in the server result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: n3") def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: n3") def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: json-ld") def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: json-ld") def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: n3") def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: n3") def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: json-ld") def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("fuseki2: Can't determine output serialization: json-ld") def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: rdf+xml") def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: rdf+xml") def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: turtle") def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: turtle") def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: n3") def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: n3") def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # json-ld is not a valid alias. Use content negotiation instead def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("fuseki2: Can't determine output content type: csv") def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("fuseki2: Can't determine output content type: csv") def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # DIFFERENT: json is an alias of json-ld def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # DIFFERENT: json is an alias of json-ld def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: rdf+xml") def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: rdf+xml") def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: turtle") def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: turtle") def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: n3") def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip("fuseki2: Can't determine output content type: n3") def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("fuseki2: Can't determine output content type: csv") def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("fuseki2: Can't determine output content type: csv") def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # DIFFERENT: json is an alias of json-ld def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # DIFFERENT: json is an alias of json-ld def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip('Fuseki Lexical error at line 8, column 45. Encountered: ":" (58), after : "\\". See #94') def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, POST) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/graphdbEnterprise__v8_9_0__rs__test.py000066400000000000000000001652571357765027600247570ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() #http://factforge.net/ # human UI http://rs.ontotext.com/sparql endpoint = "http://rs.ontotext.com/repositories/ff-news" #406 The Accept header does not include any available content types. # In the event that the specified representation format is not supported, a 406 Not Acceptable response code SHOULD be returned. # The server always looks at the Accept header of a request, and tries to generate a response in the format that the client asks for. If this fails, a 406 response is returned. prefixes = """ PREFIX pubo: PREFIX pub: PREFIX dbr: PREFIX xsd: PREFIX ff-map: """ selectQuery = """ SELECT DISTINCT ?news ?title ?date { ?news ff-map:mentionsEntity dbr:IBM . # one can change the entity here ?news pubo:creationDate ?date ; pubo:title ?title . FILTER ( (?date > "2017-09-01"^^xsd:dateTime) && (?date < "2017-09-15"^^xsd:dateTime)) } limit 100 """ selectQueryCSV_TSV = """ SELECT DISTINCT ?news ?title ?date { ?news ff-map:mentionsEntity dbr:IBM . # one can change the entity here ?news pubo:creationDate ?date ; pubo:title ?title . FILTER ( (?date > "2017-09-01"^^xsd:dateTime) && (?date < "2017-09-15"^^xsd:dateTime)) } limit 100 """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v rdfs:label ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { rdfs:label ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # graphDB uses ONLY content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ @unittest.skip("graphDB supports only Content Negotiation") def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("graphDB supports only Content Negotiation") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("graphDB supports only Content Negotiation") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip("graphDB supports only Content Negotiation") def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is text/csv @unittest.skip("graphDB supports only Content Negotiation") def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is text/csv def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is text/csv @unittest.skip("graphDB supports only Content Negotiation") def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is text/csv def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is text/csv @unittest.skip("graphDB supports only Content Negotiation") def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is text/csv def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is text/csv @unittest.skip("graphDB supports only Content Negotiation") def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is text/csv def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unknown return format for SELECT queryType (XML is sent) @unittest.skip("graphDB supports only Content Negotiation") def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/csv # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) @unittest.skip("graphDB supports only Content Negotiation") def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# @unittest.skip("graphDB supports only Content Negotiation") def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("graphDB supports only Content Negotiation") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("graphDB supports only Content Negotiation") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB not supports CSV for ASK queryType") def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB not supports CSV for ASK queryType") def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB not supports TSV for ASK queryType") def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB not supports TSV for ASK queryType") def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip("graphDB supports only Content Negotiation") def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("graphDB supports only Content Negotiation") def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # application/sparql-results+json # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # application/sparql-results+json # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("graphDB supports only Content Negotiation") def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # application/sparql-results+json # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # application/sparql-results+json # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("graphDB supports only Content Negotiation") def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # application/sparql-results+json # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # application/sparql-results+json # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip("graphDB supports only Content Negotiation") def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # application/sparql-results+json # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # application/sparql-results+json # Asking for an unknown return format for ASK queryType (XML is sent) @unittest.skip("graphDB supports only Content Negotiation") def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) @unittest.skip("graphDB supports only Content Negotiation") def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ############################################################################### ############################################################################### ################## ### CONSTRUCT #### ################## @unittest.skip("graphDB supports only Content Negotiation") def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples @unittest.skip("graphDB supports only Content Negotiation") def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples @unittest.skip("graphDB supports only Content Negotiation") def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples @unittest.skip("graphDB supports only Content Negotiation") def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples @unittest.skip("graphDB supports only Content Negotiation") def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) @unittest.skip("graphDB supports only Content Negotiation") def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ############################################################################### ############################################################################### ################# ### DESCRIBE #### ################# @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) print result.geturl() ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unknown return format for DESCRIBE queryType (XML is sent) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) @unittest.skip("graphDB supports only Content Negotiation") def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) # https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#iriRefs # A prefix declared with the PREFIX keyword may not be re-declared in the same query. @unittest.skip("GraphDB returns a QueryBadFormed Error.") def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) #MALFORMED QUERY: Lexical error at line 10, column 44. Encountered: "\\" (92), after : "" @unittest.skip("graphDB returns a QueryBadFormed Error.") def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, GET) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/lov-fuseki_on_hold.py000066400000000000000000001750311357765027600216000ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "https://lov.linkeddata.es/dataset/lov/sparql/" # Fuseki - version 1.1.1 (Build date: 2014-10-02T16:36:17+0100) prefixes = """ PREFIX vann: PREFIX voaf: PREFIX rdf: PREFIX rdfs: PREFIX skos: """ selectQuery = """ SELECT DISTINCT ?vocabPrefix ?vocabURI { GRAPH { ?vocabURI a voaf:Vocabulary. ?vocabURI vann:preferredNamespacePrefix ?vocabPrefix. }} ORDER BY ?vocabPrefix """ selectQueryCSV_TSV = """ SELECT DISTINCT ?vocabPrefix ?vocabURI { GRAPH { ?vocabURI a voaf:Vocabulary. ?vocabURI vann:preferredNamespacePrefix ?vocabPrefix. }} ORDER BY ?vocabPrefix """ askQuery = """ ASK { a } """ constructQuery = """ CONSTRUCT { _:v skos:prefLabel ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { rdfs:label ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # Fuseki uses URL parameters. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (n3 is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, and it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (n3 is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+json @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # json-ld is not a valid alias. Use content negotiation instead def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # json-ld is not a valid alias. Use content negotiation instead @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle # json is NOT an alias of json-ld in Fuseki (only in Fuseki2) def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle # json is NOT an alias of json-ld in Fuseki (only in Fuseki2) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # rdf+xml is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is not a valid alias def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) # n3 is not a valid alias @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle # json is NOT an alias of json-ld in Fuseki (only in Fuseki2) def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle # json is NOT an alias of json-ld in Fuseki (only in Fuseki2) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) @unittest.skip('The current SPARQL endpoint returns 500 on POST requests. Maybe it is not an issue of Fuseki') def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ @unittest.skip('Fuseki returns 200 instead of 400 (error code present in the returned text response)') def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() @unittest.skip('Line 10, column 40: Illegal prefix name escape: _. See #94') @unittest.skip('Fuseki returns 200 instead of 400 (error code present in the returned text response)') def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip('Lexical error at line 10, column 45. Encountered: ":" (58), after : "\\". See #94') @unittest.skip('Fuseki returns 200 instead of 400 (error code present in the returned text response)') def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, GET) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/rdf4j__geosciml__test.py000066400000000000000000001673771357765027600222600ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "http://vocabs.ands.org.au/repository/api/sparql/csiro_international-chronostratigraphic-chart_2018-revised-corrected" prefixes = """ PREFIX rdfs: PREFIX skos: """ selectQuery = """ SELECT DISTINCT ?era ?label ?notation { ?era a ; rdfs:label ?label ; skos:notation ?notation . } LIMIT 100 """ selectQueryCSV_TSV = """ SELECT DISTINCT ?era ?label ?notation { ?era a ; rdfs:label ?label ; skos:notation ?notation . } LIMIT 100 """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v rdfs:label ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { rdfs:label ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed_1 = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryBadFormed_2 = """ PREFIX prop: PREFIX res: SELECT ?lat ?not_defined WHERE { res:Budapest prop:latitude ?lat . } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # Openrdf uses ONLY content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) @unittest.skip("Openrdf supports only Content Negotiation") def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# @unittest.skip("Openrdf supports only Content Negotiation") def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Openrdf supports only Content Negotiation") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Openrdf supports only Content Negotiation") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf not supports CSV for ASK queryType. Error 406") def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf not supports CSV for ASK queryType. Error 406") def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf not supports TSV for ASK queryType. Error 406") def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf not supports TSV for ASK queryType. Error 406") def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip("Openrdf supports only Content Negotiation") def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Openrdf supports only Content Negotiation") def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Openrdf supports only Content Negotiation") def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Openrdf supports only Content Negotiation") def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Openrdf supports only Content Negotiation") def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) @unittest.skip("Openrdf supports only Content Negotiation") def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) @unittest.skip("Openrdf supports only Content Negotiation") def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ############################################################################### ############################################################################### ################## ### CONSTRUCT #### ################## @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is application/n-triples def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) @unittest.skip("Openrdf supports only Content Negotiation") def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ############################################################################### ############################################################################### ################# ### DESCRIBE #### ################# @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) print result.geturl() ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) application/n-triples def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # application/n-triples # Asking for an unknown return format for DESCRIBE queryType (XML is sent) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) @unittest.skip("Openrdf supports only Content Negotiation") def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################################################################################ def testQueryBadFormed_1(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed_1, XML, GET) @unittest.skip("Openrdf returns a result (with <200> code), instead of an error.") def testQueryBadFormed_2(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed_2, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) # https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#iriRefs # A prefix declared with the PREFIX keyword may not be re-declared in the same query. # MALFORMED QUERY: Multiple prefix declarations for prefix 'xxx' @unittest.skip("Openrdf returns a QueryBadFormed Error.") def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) #MALFORMED QUERY: Lexical error at line 10, column 44. Encountered: "\\" (92), after : "" @unittest.skip("Openrdf returns a MalformedQuery Error.") def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, GET) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/stardog__lindas__test.py000066400000000000000000001667251357765027600223560ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() # human UI https://lindas-data.ch/sparql-ui/ endpoint = "https://lindas-data.ch/sparql" prefixes = """ PREFIX rdfs: """ selectQuery = """ SELECT DISTINCT ?place ?label ?lat ?long { ?place a ; rdfs:label ?label ; ?lat ; ?long . } LIMIT 100 """ selectQueryCSV_TSV = """ SELECT DISTINCT ?place ?label ?lat ?long { ?place a ; rdfs:label ?label ; ?lat ; ?long . } LIMIT 100 """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v rdfs:label ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { rdfs:label ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed_1 = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryBadFormed_2 = """ PREFIX prop: PREFIX res: SELECT ?lat ?not_defined WHERE { res:Budapest prop:latitude ?lat . } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # Stardog uses ONLY content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ @unittest.skip("Stardog supports only Content Negotiation") def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Stardog supports only Content Negotiation") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Stardog supports only Content Negotiation") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip("Stardog supports only Content Negotiation") def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Stardog supports only Content Negotiation") def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Stardog supports only Content Negotiation") def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Stardog supports only Content Negotiation") def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Stardog supports only Content Negotiation") def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) @unittest.skip("Stardog supports only Content Negotiation") def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) @unittest.skip("Stardog supports only Content Negotiation") def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# @unittest.skip("Stardog supports only Content Negotiation") def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Stardog supports only Content Negotiation") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") @unittest.skip("Stardog supports only Content Negotiation") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog not supports CSV for ASK queryType. Error 500") def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog not supports CSV for ASK queryType. Error 500") def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog not supports TSV for ASK queryType. Error 500") def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog not supports TSV for ASK queryType. Error 500") def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) @unittest.skip("Stardog supports only Content Negotiation") def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Stardog supports only Content Negotiation") def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Stardog supports only Content Negotiation") def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Stardog supports only Content Negotiation") def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Stardog supports only Content Negotiation") def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) @unittest.skip("Stardog supports only Content Negotiation") def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) @unittest.skip("Stardog supports only Content Negotiation") def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ############################################################################### ############################################################################### ################## ### CONSTRUCT #### ################## @unittest.skip("Stardog supports only Content Negotiation") def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Stardog supports only Content Negotiation") def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Stardog supports only Content Negotiation") def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Stardog supports only Content Negotiation") def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET , onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Stardog supports only Content Negotiation") def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) @unittest.skip("Stardog supports only Content Negotiation") def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ############################################################################### ############################################################################### ################# ### DESCRIBE #### ################# @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) text/turtle @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) text/turtle def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) text/turtle @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) text/turtle def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) text/turtle @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) text/turtle def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) text/turtle @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) text/turtle def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE] results = result.convert() self.assertEqual(type(results), bytes) # text/turtle # Asking for an unknown return format for DESCRIBE queryType (XML is sent) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) @unittest.skip("Stardog supports only Content Negotiation") def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################################################################################ @unittest.skip("Stardog returns <200> code AND a MalformedQuery Error.") def testQueryBadFormed_1(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed_1, XML, GET) @unittest.skip("Stardog returns a result (with <200> code), instead of an error.") def testQueryBadFormed_2(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed_2, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) # https://www.w3.org/TR/2013/REC-sparql11-query-20130321/#iriRefs # A prefix declared with the PREFIX keyword may not be re-declared in the same query. def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) #MALFORMED QUERY: Lexical error at line 10, column 44. Encountered: "\\" (92), after : "" @unittest.skip("Stardog returns <200> code AND a MalformedQuery Error.") def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, GET) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/virtuoso__v7_20_3230__dbpedia__test.py000066400000000000000000001754021357765027600244360ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "http://dbpedia.org/sparql" prefixes = """ PREFIX rdf: PREFIX rdfs: """ selectQuery = """ SELECT ?label WHERE { rdfs:label ?label . } """ selectQueryCSV_TSV = """ SELECT ?label ?wikiPageID WHERE { rdfs:label ?label ; ?wikiPageID } """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v rdfs:label ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { rdfs:label ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # Virtuoso 7 uses URL parameters or content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml # URI generated http://dbpedia.org/sparql?query=%0A++++PREFIX+rdf%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23%3E%0A++++PREFIX+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0A%0A++++SELECT+%3Flabel%0A++++WHERE+%7B%0A++++%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FAsturias%3E+rdfs%3Alabel+%3Flabel+.%0A++++%7D%0A @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/html. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/html. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/html. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/html. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ############################################################################### ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is a valid alias def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns text/csv. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns text/csv. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ############################################################################### ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is a valid alias def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns text/csv. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns text/csv. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() @unittest.skip("Virtuoso returns a QueryBadFormed Error. See #94") def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip("Virtuoso returns a QueryBadFormed Error. See #94") def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, GET) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/virtuoso__v8_03_3313__dbpedia__test.py000066400000000000000000001753131357765027600244430ustar00rootroot00000000000000# -*- coding: utf-8 -*- #!/usr/bin/python import inspect import os import sys import unittest # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack import warnings warnings.simplefilter("always") try: from rdflib.graph import ConjunctiveGraph except ImportError: from rdflib import ConjunctiveGraph from SPARQLWrapper import SPARQLWrapper, XML, RDFXML, RDF, N3, TURTLE, JSONLD, JSON, CSV, TSV, POST, GET from SPARQLWrapper.Wrapper import _SPARQL_XML, _SPARQL_JSON, _XML, _RDF_XML, _RDF_N3, _RDF_TURTLE, _RDF_JSONLD, _CSV, _TSV from SPARQLWrapper.SPARQLExceptions import QueryBadFormed _SPARQL_SELECT_ASK_POSSIBLE = _SPARQL_XML + _SPARQL_JSON + _CSV + _TSV + _XML # only used in test _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE = _RDF_XML + _RDF_N3 + _XML + _RDF_JSONLD # only used in test. Same as Wrapper._RDF_POSSIBLE try: from urllib.error import HTTPError # Python 3 except ImportError: from urllib2 import HTTPError # Python 2 try: bytes # Python 2.6 and above except NameError: bytes = str import logging logging.basicConfig() endpoint = "http://dbpedia-live.openlinksw.com/sparql" prefixes = """ PREFIX rdf: PREFIX rdfs: """ selectQuery = """ SELECT ?label WHERE { rdfs:label ?label . } """ selectQueryCSV_TSV = """ SELECT ?label ?wikiPageID WHERE { rdfs:label ?label ; ?wikiPageID } """ askQuery = """ ASK { a ?type } """ constructQuery = """ CONSTRUCT { _:v rdfs:label ?label . _:v rdfs:comment "this is only a mock node to test library" } WHERE { rdfs:label ?label . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX prop: PREFIX res: FROM SELECT ?lat ?long WHERE { res:Budapest prop:latitude ?lat; prop:longitude ?long. } """ queryManyPrefixes = """ PREFIX conf: PREFIX meta: PREFIX rdf: PREFIX rdfs: PREFIX xsd: PREFIX owl: PREFIX dc: PREFIX dcterms: PREFIX foaf: PREFIX skos: PREFIX geo: PREFIX dbpedia: PREFIX o: PREFIX p: PREFIX yago: PREFIX units: PREFIX geonames: PREFIX prv: PREFIX prvTypes: PREFIX foo: SELECT ?label WHERE { rdfs:label ?label . } """ queryDuplicatedPrefix = """ PREFIX rdf: PREFIX rdf: SELECT ?s ?p ?o WHERE { ?s ?p ?o . } LIMIT 10 """ queryWithCommaInCurie_1 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Victoria\\,\\_British\\_Columbia . ?article ?title } """ queryWithCommaInCurie_2 = """ PREFIX dbpedia: SELECT ?article ?title WHERE { ?article ?relation dbpedia:Category\:Victoria\,\_British\_Columbia . ?article ?title } """ queryWithCommaInUri = """ SELECT ?article ?title WHERE { ?article ?relation . ?article ?title } """ class SPARQLWrapperTests(unittest.TestCase): def __generic(self, query, returnFormat, method, onlyConneg=False): # Virtuoso 7 uses URL parameters or content negotiation. sparql = SPARQLWrapper(endpoint) sparql.setQuery(prefixes + query) sparql.setReturnFormat(returnFormat) sparql.setMethod(method) sparql.setOnlyConneg(onlyConneg) try: result = sparql.query() except HTTPError: # An ugly way to get the exception, but the only one that works # both on Python 2.5 and Python 3. e = sys.exc_info()[1] if e.code == 400: sys.stdout.write("400 Bad Request, probably query is not well formed") elif e.code == 406: sys.stdout.write("406 Not Acceptable, maybe query is not well formed") else: sys.stdout.write(str(e)) sys.stdout.write("\n") return False else: return result ################################################################################ ################################################################################ ################ #### SELECT #### ################ def testSelectByGETinXML(self): result = self.__generic(selectQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinXML_Conneg(self): result = self.__generic(selectQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML(self): result = self.__generic(selectQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByPOSTinXML_Conneg(self): result = self.__generic(selectQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testSelectByGETinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinCSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByPOSTinTSV_Conneg(self): result = self.__generic(selectQueryCSV_TSV, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testSelectByGETinJSON(self): result = self.__generic(selectQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByGETinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON(self): result = self.__generic(selectQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testSelectByPOSTinJSON_Conneg(self): result = self.__generic(selectQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml # URI generated http://dbpedia.org/sparql?query=%0A++++PREFIX+rdf%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F1999%2F02%2F22-rdf-syntax-ns%23%3E%0A++++PREFIX+rdfs%3A+%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23%3E%0A%0A++++SELECT+%3Flabel%0A++++WHERE+%7B%0A++++%3Chttp%3A%2F%2Fdbpedia.org%2Fresource%2FAsturias%3E+rdfs%3Alabel+%3Flabel+.%0A++++%7D%0A @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testSelectByGETinN3_Unexpected(self): result = self.__generic(selectQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testSelectByGETinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testSelectByPOSTinN3_Unexpected(self): result = self.__generic(selectQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testSelectByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(selectQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected(self): result = self.__generic(selectQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unexpected return format for SELECT queryType (json-ld is not supported, it is not a valid alias). # Set by default None (and sending */*). # For a SELECT query type, the default return mimetype (if Accept: */* is sent) is application/sparql-results+xml def testSelectByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(selectQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow(self): result = self.__generic(selectQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByGETinUnknow_Conneg(self): result = self.__generic(selectQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow(self): result = self.__generic(selectQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for SELECT queryType (XML is sent) def testSelectByPOSTinUnknow_Conneg(self): result = self.__generic(selectQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ################################################################################ ################################################################################ ############# #### ASK #### ############# def testAskByGETinXML(self): result = self.__generic(askQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinXML_Conneg(self): result = self.__generic(askQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML(self): result = self.__generic(askQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByPOSTinXML_Conneg(self): result = self.__generic(askQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_XML], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") def testAskByGETinCSV(self): result = self.__generic(askQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinCSV_Conneg(self): result = self.__generic(askQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV(self): result = self.__generic(askQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinCSV_Conneg(self): result = self.__generic(askQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _CSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV(self): result = self.__generic(askQuery, TSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinTSV_Conneg(self): result = self.__generic(askQuery, TSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV(self): result = self.__generic(askQuery, TSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByPOSTinTSV_Conneg(self): result = self.__generic(askQuery, TSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _TSV], ct results = result.convert() self.assertEqual(type(results), bytes) def testAskByGETinJSON(self): result = self.__generic(askQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByGETinJSON_Conneg(self): result = self.__generic(askQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON(self): result = self.__generic(askQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) def testAskByPOSTinJSON_Conneg(self): result = self.__generic(askQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_JSON], ct results = result.convert() self.assertEqual(type(results), dict) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByGETinN3_Unexpected(self): result = self.__generic(askQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByGETinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByPOSTinN3_Unexpected(self): result = self.__generic(askQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/rdf+n3. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByPOSTinN3_Unexpected_Conneg(self): result = self.__generic(askQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/html. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByGETinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/html. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByGETinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/html. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByPOSTinJSONLD_Unexpected(self): result = self.__generic(askQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() # Asking for an unexpected return format for ASK queryType # Set by default None (and sending */*). # For an ASK query type, the default return mimetype (if Accept: */* is sent) is text/html @unittest.skip("Virtuoso returns text/html. It MUST return SPARQL Results Document in XML (sparql-results+xml), JSON (sparql-results+json), or CSV/TSV (text/csv or text/tab-separated-values) see http://www.w3.org/TR/sparql11-protocol/#query-success") def testAskByPOSTinJSONLD_Unexpected_Conneg(self): result = self.__generic(askQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow(self): result = self.__generic(askQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByGETinUnknow_Conneg(self): result = self.__generic(askQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow(self): result = self.__generic(askQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # Asking for an unknown return format for ASK queryType (XML is sent) def testAskByPOSTinUnknow_Conneg(self): result = self.__generic(askQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_SELECT_ASK_POSSIBLE], ct results = result.convert() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") ############################################################################### ################################################################################ ################### #### CONSTRUCT #### ################### def testConstructByGETinXML(self): result = self.__generic(constructQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinXML_Conneg(self): result = self.__generic(constructQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML(self): result = self.__generic(constructQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinXML_Conneg(self): result = self.__generic(constructQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinRDFXML(self): result = self.__generic(constructQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML(self): result = self.__generic(constructQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinRDFXML_Conneg(self): result = self.__generic(constructQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is a valid alias def testConstructByGETinTURTLE(self): result = self.__generic(constructQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testConstructByGETinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testConstructByPOSTinTURTLE(self): result = self.__generic(constructQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testConstructByPOSTinTURTLE_Conneg(self): result = self.__generic(constructQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3(self): result = self.__generic(constructQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinN3_Conneg(self): result = self.__generic(constructQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3(self): result = self.__generic(constructQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByPOSTinN3_Conneg(self): result = self.__generic(constructQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testConstructByGETinJSONLD(self): result = self.__generic(constructQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByGETinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinJSONLD(self): result = self.__generic(constructQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testConstructByPOSTinJSONLD_Conneg(self): result = self.__generic(constructQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns text/csv. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByGETinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByGETinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns text/csv. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByPOSTinCSV_Unexpected(self): result = self.__generic(constructQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testConstructByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(constructQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByGETinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByGETinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByPOSTinJSON_Unexpected(self): result = self.__generic(constructQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for CONSTRUCT queryType. # For a CONSTRUCT query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testConstructByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(constructQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow(self): result = self.__generic(constructQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByGETinUnknow_Conneg(self): result = self.__generic(constructQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow(self): result = self.__generic(constructQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for CONSTRUCT queryType (XML is sent) def testConstructByPOSTinUnknow_Conneg(self): result = self.__generic(constructQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ############################################################################### ################################################################################ ################## #### DESCRIBE #### ################## def testDescribeByGETinXML(self): result = self.__generic(describeQuery, XML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinXML_Conneg(self): result = self.__generic(describeQuery, XML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML(self): result = self.__generic(describeQuery, XML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinXML_Conneg(self): result = self.__generic(describeQuery, XML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinRDFXML(self): result = self.__generic(describeQuery, RDFXML, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinRDFXML(self): result = self.__generic(describeQuery, RDFXML, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinRDFXML_Conneg(self): result = self.__generic(describeQuery, RDFXML, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_XML], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # turtle is a valid alias def testDescribeByGETinTURTLE(self): result = self.__generic(describeQuery, TURTLE, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testDescribeByGETinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testDescribeByPOSTinTURTLE(self): result = self.__generic(describeQuery, TURTLE, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) # turtle is a valid alias def testDescribeByPOSTinTURTLE_Conneg(self): result = self.__generic(describeQuery, TURTLE, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_TURTLE], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3(self): result = self.__generic(describeQuery, N3, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinN3_Conneg(self): result = self.__generic(describeQuery, N3, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3(self): result = self.__generic(describeQuery, N3, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByPOSTinN3_Conneg(self): result = self.__generic(describeQuery, N3, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_N3], ct results = result.convert() self.assertEqual(type(results), bytes) def testDescribeByGETinJSONLD(self): result = self.__generic(describeQuery, JSONLD, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByGETinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD(self): result = self.__generic(describeQuery, JSONLD, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) def testDescribeByPOSTinJSONLD_Conneg(self): result = self.__generic(describeQuery, JSONLD, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _RDF_JSONLD], "returned Content-Type='%s'." %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns text/csv. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByGETinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns text/csv. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByPOSTinCSV_Unexpected(self): result = self.__generic(describeQuery, CSV, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle def testDescribeByPOSTinCSV_Unexpected_Conneg(self): result = self.__generic(describeQuery, CSV, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), bytes) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByGETinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByPOSTinJSON_Unexpected(self): result = self.__generic(describeQuery, JSON, POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unexpected return format for DESCRIBE queryType. # For a DESCRIBE query type, the default return mimetype (if Accept: */* is sent) is text/turtle @unittest.skip("Virtuoso returns application/sparql-results+json. It MUST return an RDF graph [RDF-CONCEPTS] serialized, for example, in the RDF/XML syntax [RDF-XML], or an equivalent RDF graph serialization, for SPARQL Query forms DESCRIBE and CONSTRUCT). See http://www.w3.org/TR/sparql11-protocol/#query-success") def testDescribeByPOSTinJSON_Unexpected_Conneg(self): result = self.__generic(describeQuery, JSON, POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], "returned Content-Type='%s'. Expected fail due to Virtuoso configuration" %(ct) results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow(self): result = self.__generic(describeQuery, "foo", GET) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByGETinUnknow_Conneg(self): result = self.__generic(describeQuery, "foo", GET, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow(self): result = self.__generic(describeQuery, "bar", POST) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) # Asking for an unknown return format for DESCRIBE queryType (XML is sent) def testDescribeByPOSTinUnknow_Conneg(self): result = self.__generic(describeQuery, "bar", POST, onlyConneg=True) ct = result.info()["content-type"] assert True in [one in ct for one in _SPARQL_DESCRIBE_CONSTRUCT_POSSIBLE], ct results = result.convert() self.assertEqual(type(results), ConjunctiveGraph) ################################################################################ ################################################################################ ################################################################################ def testQueryBadFormed(self): self.assertRaises(QueryBadFormed, self.__generic, queryBadFormed, XML, GET) def testQueryManyPrefixes(self): result = self.__generic(queryManyPrefixes, XML, GET) def testQueryDuplicatedPrefix(self): result = self.__generic(queryDuplicatedPrefix, XML, GET) def testKeepAlive(self): sparql = SPARQLWrapper(endpoint) sparql.setQuery('SELECT * WHERE {?s ?p ?o} LIMIT 10') sparql.setReturnFormat(JSON) sparql.setMethod(GET) sparql.setUseKeepAlive() sparql.query() sparql.query() def testQueryWithComma_1(self): result = self.__generic(queryWithCommaInCurie_1, XML, GET) @unittest.skip("Virtuoso returns a QueryBadFormed Error. See #94") def testQueryWithComma_2(self): result = self.__generic(queryWithCommaInCurie_2, XML, GET) def testQueryWithComma_3(self): result = self.__generic(queryWithCommaInUri, XML, GET) if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/test/wrapper_test.py000066400000000000000000001122251357765027600205250ustar00rootroot00000000000000# -*- coding: utf-8 -*- import inspect import os import sys import logging import unittest import urllib2 from urlparse import urlparse, parse_qsl, parse_qs from urllib2 import Request import time logging.basicConfig() # prefer local copy to the one which is installed # hack from http://stackoverflow.com/a/6098238/280539 _top_level_path = os.path.realpath(os.path.abspath(os.path.join( os.path.split(inspect.getfile(inspect.currentframe()))[0], ".." ))) if _top_level_path not in sys.path: sys.path.insert(0, _top_level_path) # end of hack # we don't want to let Wrapper do real web-requests. so, we are… # constructing a simple Mock! from urllib2 import HTTPError from io import StringIO import warnings warnings.simplefilter("always") import SPARQLWrapper.Wrapper as _victim from SPARQLWrapper import SPARQLWrapper from SPARQLWrapper import XML, GET, POST, JSON, JSONLD, N3, TURTLE, RDF, SELECT, INSERT, RDFXML, CSV, TSV from SPARQLWrapper import URLENCODED, POSTDIRECTLY from SPARQLWrapper import BASIC, DIGEST from SPARQLWrapper.Wrapper import QueryResult, QueryBadFormed, EndPointNotFound, EndPointInternalError, Unauthorized, URITooLong class FakeResult(object): def __init__(self, request): self.request = request def urlopener(request): return FakeResult(request) def urlopener_error_generator(code): def urlopener_error(request): raise HTTPError(request.get_full_url, code, '', {}, StringIO(u'')) return urlopener_error def urlopener_check_data_encoding(request): if sys.version < '3': # have to write it like this, for 2to3 compatibility if isinstance(request.data, unicode): raise TypeError else: if isinstance(request.data, str): raise TypeError # DONE class TestCase(unittest.TestCase): def assertIsInstance(self, obj, cls, msg=None, *args, **kwargs): """Python < v2.7 compatibility. Assert 'obj' is instance of 'cls'""" try: f = super(TestCase, self).assertIsInstance except AttributeError: self.assertTrue(isinstance(obj, cls), *args, **kwargs) else: f(obj, cls, *args, **kwargs) def assertIsNone(self, obj, msg=None, *args, **kwargs): """Python < v2.7 compatibility. Assert 'obj' is None""" try: f = super(TestCase, self).assertIsNone except AttributeError: self.assertEqual(obj, None, *args, **kwargs) else: f(obj, *args, **kwargs) class SPARQLWrapper_Test(TestCase): @staticmethod def _get_request(wrapper): return wrapper.query().response.request # possible due to mock above @staticmethod def _get_parameters_from_request(request): if request.get_method() == 'GET': pieces_str = urlparse(request.get_full_url()).query else: if sys.version < '3': pieces_str = request.data else: pieces_str = request.data.decode('ascii') return parse_qs(pieces_str) @staticmethod def _get_request_parameters(wrapper): request = SPARQLWrapper_Test._get_request(wrapper) parameters = SPARQLWrapper_Test._get_parameters_from_request(request) return parameters @staticmethod def _get_request_parameters_as_bytes(wrapper): request = SPARQLWrapper_Test._get_request(wrapper) parameters = SPARQLWrapper_Test._get_parameters_from_request(request) if sys.version < '3': return parameters else: result = {} for k, vs in parameters.iteritems(): result[k] = [v.encode('utf-8') for v in vs] return result @classmethod def setUpClass(cls): urllib2._opener = None # clear value. Due to the order of test execution, the value of urllib2._opener contains, for instance, keepalive.keepalive.HTTPHandler def setUp(self): self.wrapper = SPARQLWrapper(endpoint='http://example.org/sparql') _victim.urlopener = urlopener def testConstructor(self): try: SPARQLWrapper() self.fail("SPARQLWrapper constructor should fail without arguments") except TypeError: pass wrapper = SPARQLWrapper(endpoint='http://example.org/sparql/') self.assertEqual(XML, wrapper.returnFormat, 'default return format is XML') self.assertTrue( wrapper.agent.startswith('sparqlwrapper'), 'default user-agent should start with "sparqlwrapper"' ) wrapper = SPARQLWrapper(endpoint='http://example.org/sparql/', returnFormat='wrongformat') self.assertEqual(XML, wrapper.returnFormat, 'default return format is XML') wrapper = SPARQLWrapper(endpoint='http://example.org/sparql/', defaultGraph='http://example.org/default') parameters = self._get_request_parameters(wrapper) self.assertEqual( ['http://example.org/default'], parameters.get('default-graph-uri'), 'default graph is set' ) def testReset(self): self.wrapper.setMethod(POST) self.wrapper.setQuery('CONSTRUCT WHERE {?a ?b ?c}') self.wrapper.setReturnFormat(N3) self.wrapper.addParameter('a', 'b') self.wrapper.setOnlyConneg(True) request = self._get_request(self.wrapper) parameters = self._get_parameters_from_request(request) onlyConneg = self.wrapper.onlyConneg self.assertEqual('POST', request.get_method()) self.assertTrue(parameters['query'][0].startswith('CONSTRUCT')) self.assertTrue('rdf+n3' in request.get_header('Accept')) self.assertTrue('a' in parameters) self.assertTrue(onlyConneg) self.wrapper.resetQuery() request = self._get_request(self.wrapper) parameters = self._get_parameters_from_request(request) onlyConneg = self.wrapper.onlyConneg self.assertEqual('GET', request.get_method()) self.assertTrue(parameters['query'][0].startswith('SELECT')) self.assertFalse('rdf+n3' in request.get_header('Accept')) self.assertTrue('sparql-results+xml' in request.get_header('Accept')) self.assertFalse('a' in parameters) self.assertFalse('a' in parameters) self.assertTrue(onlyConneg) def testSetReturnFormat(self): with warnings.catch_warnings(record=True) as w: self.wrapper.setReturnFormat('nonexistent format') self.assertEqual(1, len(w), "Warning due to non expected format") self.assertEqual(XML, self.wrapper.query().requestedFormat) self.wrapper.setReturnFormat(JSON) self.assertEqual(JSON, self.wrapper.query().requestedFormat) try: import rdflib_jsonld self.wrapper.setReturnFormat(JSONLD) self.assertEqual(JSONLD, self.wrapper.query().requestedFormat) except ImportError: self.assertRaises(ValueError, self.wrapper.setReturnFormat, JSONLD) def testsSupportsReturnFormat(self): self.assertTrue(self.wrapper.supportsReturnFormat(XML)) self.assertTrue(self.wrapper.supportsReturnFormat(JSON)) self.assertTrue(self.wrapper.supportsReturnFormat(TURTLE)) self.assertTrue(self.wrapper.supportsReturnFormat(N3)) self.assertTrue(self.wrapper.supportsReturnFormat(RDF)) self.assertTrue(self.wrapper.supportsReturnFormat(RDFXML)) self.assertTrue(self.wrapper.supportsReturnFormat(CSV)) self.assertTrue(self.wrapper.supportsReturnFormat(TSV)) self.assertFalse(self.wrapper.supportsReturnFormat('nonexistent format')) try: import rdflib_jsonld self.assertTrue(self.wrapper.supportsReturnFormat(JSONLD)) except ImportError: self.assertFalse(self.wrapper.supportsReturnFormat(JSONLD)) def testAddParameter(self): self.assertFalse(self.wrapper.addParameter('query', 'dummy')) self.assertTrue(self.wrapper.addParameter('param1', 'value1')) self.assertTrue(self.wrapper.addParameter('param1', 'value2')) self.assertTrue(self.wrapper.addParameter('param2', 'value2')) pieces = self._get_request_parameters(self.wrapper) self.assertTrue('param1' in pieces) self.assertEqual(['value1', 'value2'], pieces['param1']) self.assertTrue('param2' in pieces) self.assertEqual(['value2'], pieces['param2']) self.assertNotEqual(['dummy'], 'query') def testSetCredentials(self): request = self._get_request(self.wrapper) self.assertFalse(request.has_header('Authorization')) self.wrapper.setCredentials('login', 'password') request = self._get_request(self.wrapper) self.assertTrue(request.has_header('Authorization')) # expected header for login:password # should succeed for python 3 since pull request #72 self.assertEqual("Basic bG9naW46cGFzc3dvcmQ=", request.get_header('Authorization')) def testAddCustomHttpHeader(self): request = self._get_request(self.wrapper) self.assertFalse(request.has_header('Foo')) # Add new header field name self.wrapper.addCustomHttpHeader('Foo', 'bar') request = self._get_request(self.wrapper) self.assertTrue(request.has_header('Foo')) self.assertEqual("bar", request.get_header('Foo')) # Override a new field name self.wrapper.addCustomHttpHeader('Foo', 'bar') request = self._get_request(self.wrapper) self.assertTrue(request.has_header('Foo')) self.assertEqual("bar", request.get_header('Foo')) self.wrapper.addCustomHttpHeader('Foo', 'bar_2') request = self._get_request(self.wrapper) self.assertTrue(request.has_header('Foo')) self.assertEqual("bar_2", request.get_header('Foo')) # Override header field name self.wrapper.addCustomHttpHeader('User-agent', 'Another UA') request = self._get_request(self.wrapper) self.assertEqual("Another UA", request.get_header('User-agent')) def testClearCustomHttpHeader(self): request = self._get_request(self.wrapper) self.assertFalse(request.has_header('Foo')) # Add new header field name self.wrapper.addCustomHttpHeader('Foo_1', 'bar_1') self.wrapper.addCustomHttpHeader('Foo_2', 'bar_2') self.wrapper.addCustomHttpHeader('Foo_3', 'bar_3') self.assertFalse(self.wrapper.clearCustomHttpHeader('Foo_4')) self.assertTrue(self.wrapper.clearCustomHttpHeader('Foo_3')) customHttpHeaders = self.wrapper.customHttpHeaders self.assertTrue('Foo_1' in customHttpHeaders) self.assertTrue('Foo_2' in customHttpHeaders) self.assertEqual('bar_1', customHttpHeaders['Foo_1']) self.assertEqual('bar_2', customHttpHeaders['Foo_2']) self.assertFalse(self.wrapper.clearCustomHttpHeader('Foo_3'), 'already cleaned') def testSetHTTPAuth(self): self.assertRaises(TypeError, self.wrapper.setHTTPAuth, 123) self.wrapper.setCredentials('login', 'password') request = self._get_request(self.wrapper) self.assertTrue(request.has_header('Authorization')) self.assertIsNone(urllib2._opener) self.wrapper.setHTTPAuth(DIGEST) self.assertIsNone(urllib2._opener) request = self._get_request(self.wrapper) self.assertFalse(request.has_header('Authorization')) self.assertEqual(self.wrapper.http_auth, DIGEST) self.assertIsInstance(urllib2._opener, urllib2.OpenerDirector) self.wrapper.setHTTPAuth(DIGEST) self.wrapper.setCredentials('login', 'password') request = self._get_request(self.wrapper) self.assertEqual(self.wrapper.http_auth, DIGEST) self.assertEqual(self.wrapper.user, "login") self.assertEqual(self.wrapper.passwd, "password") self.assertEqual(self.wrapper.realm, "SPARQL") self.assertNotEqual(self.wrapper.realm, "SPARQL Endpoint") self.wrapper.setHTTPAuth(DIGEST) self.wrapper.setCredentials('login', 'password', realm="SPARQL Endpoint") request = self._get_request(self.wrapper) self.assertEqual(self.wrapper.http_auth, DIGEST) self.assertEqual(self.wrapper.user, "login") self.assertEqual(self.wrapper.passwd, "password") self.assertEqual(self.wrapper.realm, "SPARQL Endpoint") self.assertNotEqual(self.wrapper.realm, "SPARQL") self.assertRaises(ValueError, self.wrapper.setHTTPAuth, 'OAuth') self.wrapper.http_auth = "OAuth" self.assertRaises(NotImplementedError, self._get_request, self.wrapper) def testSetQuery(self): self.wrapper.setQuery('PREFIX example: SELECT * WHERE {?s ?p ?v}') self.assertEqual(SELECT, self.wrapper.queryType) self.wrapper.setQuery('PREFIX e: INSERT {e:a e:b e:c}') self.assertEqual(INSERT, self.wrapper.queryType) self.wrapper.setQuery("""#CONSTRUCT {?s ?p ?o} SELECT ?s ?p ?o WHERE {?s ?p ?o}""") self.assertEqual(SELECT, self.wrapper.queryType) with warnings.catch_warnings(record=True) as w: self.wrapper.setQuery('UNKNOWN {e:a e:b e:c}') self.assertEqual(SELECT, self.wrapper.queryType, 'unknown queries result in SELECT') def testSetQueryEncodingIssues(self): #further details from issue #35 query = u'INSERT DATA { "これはテストです" }' query_bytes = query.encode('utf-8') self.wrapper.setMethod(POST) self.wrapper.setRequestMethod(POSTDIRECTLY) self.wrapper.setQuery(query) request = self._get_request(self.wrapper) self.assertEquals(query_bytes, request.data) self.wrapper.setQuery(query_bytes) request = self._get_request(self.wrapper) self.assertEquals(query_bytes, request.data) self.wrapper.setRequestMethod(URLENCODED) self.wrapper.setQuery(query) parameters = self._get_request_parameters_as_bytes(self.wrapper) self.assertEquals(query_bytes, parameters['update'][0]) self.wrapper.setQuery(query_bytes) parameters = self._get_request_parameters_as_bytes(self.wrapper) self.assertEquals(query_bytes, parameters['update'][0]) try: self.wrapper.setQuery(query.encode('sjis')) self.fail() except UnicodeDecodeError: self.assertTrue(True) try: self.wrapper.setQuery({'foo': 'bar'}) self.fail() except TypeError: self.assertTrue(True) def testSetTimeout(self): self.wrapper.setTimeout(10) self.assertEqual(10, self.wrapper.timeout) self.wrapper.resetQuery() self.assertEqual(None, self.wrapper.timeout) def testClearParameter(self): self.wrapper.addParameter('param1', 'value1') self.wrapper.addParameter('param1', 'value2') self.wrapper.addParameter('param2', 'value2') self.assertFalse(self.wrapper.clearParameter('query')) self.assertTrue(self.wrapper.clearParameter('param1')) pieces = self._get_request_parameters(self.wrapper) self.assertFalse('param1' in pieces) self.assertTrue('param2' in pieces) self.assertEqual(['value2'], pieces['param2']) self.assertFalse(self.wrapper.clearParameter('param1'), 'already cleaned') def testSetMethod(self): self.wrapper.setMethod(POST) request = self._get_request(self.wrapper) self.assertEqual("POST", request.get_method()) self.wrapper.setMethod(GET) request = self._get_request(self.wrapper) self.assertEqual("GET", request.get_method()) def testSetRequestMethod(self): self.assertEqual(URLENCODED, self.wrapper.requestMethod) self.wrapper.setRequestMethod(POSTDIRECTLY) self.assertEqual(POSTDIRECTLY, self.wrapper.requestMethod) def testIsSparqlUpdateRequest(self): self.wrapper.setQuery('DELETE WHERE {?s ?p ?o}') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('DELETE DATA { }') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery(""" PREFIX example: BASE DELETE WHERE {?s ?p ?o} """) self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('WITH DELETE DATA { }') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('INSERT DATA { }') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('WITH INSERT DATA { }') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('CREATE GRAPH ') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('CLEAR GRAPH ') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('DROP GRAPH ') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('MOVE GRAPH TO GRAPH ') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('LOAD INTO GRAPH ') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('COPY TO GRAPH ') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) self.wrapper.setQuery('ADD TO GRAPH ') self.assertTrue(self.wrapper.isSparqlUpdateRequest()) def testIsSparqlQueryRequest(self): self.wrapper.setQuery('SELECT * WHERE {?s ?p ?o}') self.assertTrue(self.wrapper.isSparqlQueryRequest()) self.wrapper.setQuery(""" PREFIX example: BASE ASK WHERE {?s ?p ?o} """) self.assertTrue(self.wrapper.isSparqlQueryRequest()) self.assertFalse(self.wrapper.isSparqlUpdateRequest()) def testQuery(self): qr = self.wrapper.query() self.assertTrue(isinstance(qr, QueryResult)) request = qr.response.request # possible due to mock above self.assertTrue(isinstance(request, Request)) parameters = self._get_parameters_from_request(request) self.assertTrue('query' in parameters) self.assertTrue('update' not in parameters) self.wrapper.setMethod(POST) self.wrapper.setQuery('PREFIX e: INSERT {e:a e:b e:c}') parameters = self._get_request_parameters(self.wrapper) self.assertTrue('update' in parameters) self.assertTrue('query' not in parameters) #_returnFormatSetting = ["format", "output", "results"] self.assertTrue('format' not in parameters) self.assertTrue('output' not in parameters) self.assertTrue('results' not in parameters) _victim.urlopener = urlopener_error_generator(400) try: self.wrapper.query() self.fail('should have raised exception') except QueryBadFormed as e: # TODO: check exception-format pass except: self.fail('got wrong exception') _victim.urlopener = urlopener_error_generator(401) try: self.wrapper.query() self.fail('should have raised exception') except Unauthorized as e: # TODO: check exception-format pass except: self.fail('got wrong exception') _victim.urlopener = urlopener_error_generator(404) try: self.wrapper.query() self.fail('should have raised exception') except EndPointNotFound as e: # TODO: check exception-format pass except: self.fail('got wrong exception') _victim.urlopener = urlopener_error_generator(414) try: self.wrapper.query() self.fail('should have raised exception') except URITooLong as e: # TODO: check exception-format pass except: self.fail('got wrong exception') _victim.urlopener = urlopener_error_generator(500) try: self.wrapper.query() self.fail('should have raised exception') except EndPointInternalError as e: # TODO: check exception-format pass except: self.fail('got wrong exception') _victim.urlopener = urlopener_error_generator(999) try: self.wrapper.query() self.fail('should have raised exception') except HTTPError as e: # TODO: check exception-format pass except: self.fail('got wrong exception') def testQueryEncoding(self): query = 'INSERT DATA { "é" }' wrapper = SPARQLWrapper('http://example.com:3030/example') wrapper.setMethod(POST) wrapper.setRequestMethod(URLENCODED) wrapper.setQuery(query) _victim.urlopener = urlopener_check_data_encoding wrapper.query() def testQueryAndConvert(self): _oldQueryResult = _victim.QueryResult class FakeQueryResult(object): def __init__(self, result): pass def convert(self): return True try: _victim.QueryResult = FakeQueryResult result = self.wrapper.queryAndConvert() self.assertEqual(True, result) finally: _victim.QueryResult = _oldQueryResult def testComments(self): # see issue #32 self.wrapper.setQuery(""" # this is a comment select * where { ?s ?p ?o } """) self.assertTrue(self.wrapper.isSparqlQueryRequest()) def testHashInPrefixes(self): # see issue #77 self.wrapper.setQuery(""" PREFIX rdfs: select * where { ?s ?p ?o } """) self.assertTrue(self.wrapper.isSparqlQueryRequest()) def testHashInPrefixComplex(self): # see issue #77 self.wrapper.setQuery(""" PREFIX rdf: PREFIX rdfs: PREFIX weather: PREFIX dbo: PREFIX dbr: PREFIX dbp: PREFIX xml: PREFIX xsd: SELECT DISTINCT ?location ?cityid ?timezone ?label WHERE { ?location weather:cityid ?cityid . ?location weather:timezone ?timezone . ?location rdfs:label ?label . } """) self.assertTrue(self.wrapper.isSparqlQueryRequest()) def testHashWithNoComments(self): # see issue #77 query = """ PREFIX rdf: SELECT * WHERE { ?s ?p ?o . } """ parsed_query = self.wrapper._cleanComments(query) self.assertEquals(query, parsed_query) def testCommentBeginningLine(self): # see issue #77 query = """ PREFIX rdf: # a comment SELECT * WHERE { ?s ?p ?o . } """ expected_parsed_query = """ PREFIX rdf: SELECT * WHERE { ?s ?p ?o . } """ parsed_query = self.wrapper._cleanComments(query) self.assertEquals(expected_parsed_query, parsed_query) def testCommentEmtpyLine(self): # see issue #77 query = """ PREFIX rdf: # a comment SELECT * WHERE { ?s ?p ?o . } """ expected_parsed_query = """ PREFIX rdf: SELECT * WHERE { ?s ?p ?o . } """ parsed_query = self.wrapper._cleanComments(query) self.assertEquals(expected_parsed_query, parsed_query) def testCommentsFirstLine(self): # see issue #77 query = """#CONSTRUCT {?s ?p ?o} SELECT ?s ?p ?o WHERE {?s ?p ?o}""" expected_parsed_query = """ SELECT ?s ?p ?o WHERE {?s ?p ?o}""" parsed_query = self.wrapper._cleanComments(query) self.assertEquals(expected_parsed_query, parsed_query) @unittest.skip("issue #80") def testCommentAfterStatements(self): # see issue #77 query = """ PREFIX rdf: SELECT * WHERE { # this is the where condition ?s ?p ?o . } """ expected_parsed_query = """ PREFIX rdf: SELECT * WHERE { ?s ?p ?o . } """ parsed_query = self.wrapper._cleanComments(query) self.assertEquals(expected_parsed_query, parsed_query) def testSingleLineQueryLine(self): # see issue #74 query = "prefix whatever: ASK { ?s ?p ?o }" parsed_query = self.wrapper._cleanComments(query) self.assertEquals(query, parsed_query) self.wrapper.setQuery(query) self.assertTrue(self.wrapper.isSparqlQueryRequest()) def testOnlyConneg(self): # see issue #82 query = "prefix whatever: ASK { ?s ?p ?o }" self.wrapper.setOnlyConneg(False) self.wrapper.setQuery(query) request = self._get_request(self.wrapper) request_params = dict(parse_qsl(urlparse(request.get_full_url()).query)) for returnFormatSetting in ["format", "output", "results"]: # Obviously _returnFormatSetting is not accessible from SPARQLWrapper, so we copy&paste the possible values self.assertTrue(returnFormatSetting in request_params, "URL parameter '%s' was not sent, and it was expected" %returnFormatSetting) #ONLY Content Negotiation self.wrapper.resetQuery() self.wrapper.setOnlyConneg(True) self.wrapper.setQuery(query) request = self._get_request(self.wrapper) request_params = dict(parse_qsl(urlparse(request.get_full_url()).query)) for returnFormatSetting in ["format", "output", "results"]: # Obviously _returnFormatSetting is not accessible from SPARQLWrapper, so we copy&paste the possible values self.assertFalse(returnFormatSetting in request_params, "URL parameter '%s' was sent, and it was not expected (only Content Negotiation)" %returnFormatSetting) class QueryResult_Test(unittest.TestCase): def testConstructor(self): qr = QueryResult('result') self.assertEqual('result', qr.response) try: format = qr.requestedFormat self.fail('format is not supposed to be set') except: pass qr = QueryResult(('result', 'format')) self.assertEqual('result', qr.response) self.assertEqual('format', qr.requestedFormat) def testProxyingToResponse(self): class FakeResponse(object): def __init__(self): self.geturl_called = False self.info_called = False self.iter_called = False self.next_called = False def geturl(self): self.geturl_called = True def info(self): self.info_called = True return {"key": "value"} def __iter__(self): self.iter_called = True def next(self): self.next_called = True result = FakeResponse() qr = QueryResult(result) qr.geturl() qr.__iter__() qr.next() self.assertTrue(result.geturl_called) self.assertTrue(result.iter_called) self.assertTrue(result.next_called) info = qr.info() self.assertTrue(result.info_called) self.assertEqual('value', info.__getitem__('KEY'), 'keys should be case-insensitive') def testConvert(self): class FakeResponse(object): def __init__(self, content_type): self.content_type = content_type def info(self): return {"Content-type": self.content_type} def read(self, len): return '' def _mime_vs_type(mime, requested_type): """ :param mime: mimetype/Content-Type of the response :param requested_type: requested mimetype (alias) :return: number of warnings produced by combo """ with warnings.catch_warnings(record=True) as w: qr = QueryResult((FakeResponse(mime), requested_type)) try: qr.convert() except: pass return len(w) # In the cases of "application/ld+json" and "application/rdf+xml", the # RDFLib raised a warning because the manually created QueryResult has no real # response value (implemented a fake read). # "WARNING:rdflib.term: does not look like a valid URI, trying to serialize this will break." self.assertEqual(0, _mime_vs_type("application/sparql-results+xml", XML)) self.assertEqual(0, _mime_vs_type("application/sparql-results+json", JSON)) self.assertEqual(0, _mime_vs_type("text/n3", N3)) self.assertEqual(0, _mime_vs_type("text/turtle", TURTLE)) self.assertEqual(0, _mime_vs_type("application/turtle", TURTLE)) self.assertEqual(0, _mime_vs_type("application/ld+json", JSON)) # Warning self.assertEqual(0, _mime_vs_type("application/ld+json", JSONLD)) # Warning self.assertEqual(0, _mime_vs_type("application/rdf+xml", XML)) # Warning self.assertEqual(0, _mime_vs_type("application/rdf+xml", RDF)) # Warning self.assertEqual(0, _mime_vs_type("application/rdf+xml", RDFXML)) # Warning self.assertEqual(0, _mime_vs_type("text/csv", CSV)) self.assertEqual(0, _mime_vs_type("text/tab-separated-values", TSV)) self.assertEqual(0, _mime_vs_type("application/xml", XML)) self.assertEqual(1, _mime_vs_type("application/x-foo-bar", XML), "invalid mime") self.assertEqual(1, _mime_vs_type("application/sparql-results+xml", N3)) self.assertEqual(1, _mime_vs_type("application/sparql-results+json", XML)) self.assertEqual(1, _mime_vs_type("text/n3", JSON)) self.assertEqual(1, _mime_vs_type("text/turtle", XML)) self.assertEqual(1, _mime_vs_type("application/ld+json", XML)) # Warning self.assertEqual(1, _mime_vs_type("application/ld+json", N3)) # Warning self.assertEqual(1, _mime_vs_type("application/rdf+xml", JSON)) # Warning self.assertEqual(1, _mime_vs_type("application/rdf+xml", N3)) # Warning def testPrint_results(self): """ print_results() is only allowed for JSON return format. """ class FakeResponse(object): def __init__(self, content_type): self.content_type = content_type def info(self): return {"Content-type": self.content_type} def read(self, len): return '' def _print_results(mime): """ :param mime: mimetype/Content-Type of the response :return: number of warnings produced by combo """ with warnings.catch_warnings(record=True) as w: qr = QueryResult(FakeResponse(mime)) try: qr.print_results() except: pass return len(w) self.assertEqual(0, _print_results("application/sparql-results+json")) self.assertEqual(0, _print_results("application/json")) self.assertEqual(0, _print_results("text/javascript")) self.assertEqual(0, _print_results("application/javascript")) self.assertEqual(1, _print_results("application/sparql-results+xml")) self.assertEqual(1, _print_results("application/xml")) self.assertEqual(1, _print_results("application/rdf+xml")) self.assertEqual(1, _print_results("application/turtle")) self.assertEqual(1, _print_results("text/turtle")) self.assertEqual(1, _print_results("text/rdf+n3")) self.assertEqual(1, _print_results("application/n-triples")) self.assertEqual(1, _print_results("application/n3")) self.assertEqual(1, _print_results("text/n3")) self.assertEqual(1, _print_results("text/csv")) self.assertEqual(1, _print_results("text/tab-separated-values")) self.assertEqual(1, _print_results("application/ld+json")) self.assertEqual(1, _print_results("application/x-json+ld")) self.assertEqual(2, _print_results("application/x-foo-bar")) class QueryType_Time_Test(unittest.TestCase): def testQueries(self): sparql = SPARQLWrapper("http://example.org/sparql") queries = [] queries.append(""" PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: FROM SELECT ?s ?p ?o WHERE { ?s ?p ?o. }""") queries.append("""PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: FROM SELECT ?s ?p ?o WHERE { ?s ?p ?o. }""") queries.append("""PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: FROM SELECT ?s ?p ?o WHERE { ?s ?p ?o. }""") queries.append("""PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: SELECT ?s ?p ?o WHERE { ?s ?p ?o. }""") queries.append(""" PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: SELECT ?s ?p ?o WHERE { ?s ?p ?o. }""") queries.append(""" FROM SELECT ?s ?p ?o WHERE { ?s ?p ?o. }""") queries.append(""" PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: FROM SELECT ?s ?p ?o WHERE { ?s ?p ?o. }""") queries.append("""PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: PREFIX a: PREFIX b: PREFIX c: PREFIX d: PREFIX e: PREFIX f: PREFIX g: PREFIX h: FROM SELECT ?s ?p ?o WHERE { ?s ?p ?o. }""") for query in queries: start_time = time.time() sparql.setQuery(query) self.assertTrue((time.time()-start_time)<0.001) # less than 0.001 second if __name__ == "__main__": unittest.main() sparqlwrapper-1.8.5/tests.sh000077500000000000000000000004241357765027600161530ustar00rootroot00000000000000#!/bin/bash PYTHON_VERSION=`python -c "import platform; print(int(platform.python_version()[:1]))"` VERSION_THRESHOLD=3 echo "running tests on python $PYTHON_VERSION.x..." if [[ ${PYTHON_VERSION} -ge ${VERSION_THRESHOLD} ]]; then bash ./run_tests_py3.sh else nosetests fi