pax_global_header00006660000000000000000000000064142134743140014515gustar00rootroot0000000000000052 comment=9ac5b51787d338817b56f192da6eacac97f50acb sparqlwrapper-2.0.0/000077500000000000000000000000001421347431400144175ustar00rootroot00000000000000sparqlwrapper-2.0.0/.github/000077500000000000000000000000001421347431400157575ustar00rootroot00000000000000sparqlwrapper-2.0.0/.github/workflows/000077500000000000000000000000001421347431400200145ustar00rootroot00000000000000sparqlwrapper-2.0.0/.github/workflows/test.yml000066400000000000000000000023161421347431400215200ustar00rootroot00000000000000name: Test on: push: branches: ["master"] pull_request: workflow_dispatch: jobs: test: runs-on: ubuntu-latest strategy: fail-fast: false max-parallel: 1 matrix: python-version: ["3.7", "3.8", "3.9", "3.10"] steps: - uses: actions/checkout@v2 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | pip install -U pip pip install '.[dev]' - name: Mypy run: | mypy --show-error-context --show-error-codes - name: Test [wrapper] if: ${{ always() }} run: | python -m unittest test/test_wrapper.py -v - name: Test [all] run: | python -m unittest -v |& tee log.txt grep '^FAIL:' log.txt > fails.txt # if all failures is not raised in `test.test_wrapper`: if [ "$(grep 'test.test_wrapper' fails.txt | wc -l)" -ne "$(wc -l < fails.txt)" ]; then exit 1 else echo 'All of the above failures are maybe false errors.' echo 'See: https://github.com/RDFLib/sparqlwrapper/issues/192' fi sparqlwrapper-2.0.0/.gitignore000066400000000000000000000001521421347431400164050ustar00rootroot00000000000000*~ *.pyc SPARQLWrapper.egg-info build dist doc .idea *.iml .project .pydevproject .settings/ .venv/ .tox/ sparqlwrapper-2.0.0/.readthedocs.yaml000066400000000000000000000003531421347431400176470ustar00rootroot00000000000000--- # https://docs.readthedocs.io/en/stable/config-file/v2.html version: 2 formats: all build: os: ubuntu-20.04 tools: python: "3.7" python: install: - method: pip path: . extra_requirements: - docs sparqlwrapper-2.0.0/AUTHORS.md000066400000000000000000000052451421347431400160740ustar00rootroot00000000000000# 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 See https://github.com/RDFLib/sparqlwrapper/graphs/contributors * [@eggplants]https://github.com/eggplants: most things to make 2.0.0 happen * 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-2.0.0/ChangeLog.txt000066400000000000000000000145451421347431400170200ustar00rootroot00000000000000SPARQLWrapper's changelog ========================= 2022-03-14 2.0.0 ----------------- - Ported codebase to Python 3. Dropped support for Python 2 - Removed nosetest in favour of unittest - Added a CLI: ``rqw`` - Updated for RDFLib >= 6.1.1 - Added type hints Special thanks to `@eggplants `_ for making this release happen. 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-2.0.0/LICENSE.txt000066400000000000000000000041261421347431400162450ustar00rootroot00000000000000SPARQL 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-2.0.0/MANAGEMENT.md000066400000000000000000000027131421347431400163600ustar00rootroot00000000000000# 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 sdist && twine upload dist/* Please, don't forget to increment to the next module (`SPARQLWrapper/__init__.py` file). ### Documentation In order to provide offline 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 Previously, [epydoc](http://epydoc.sourceforge.net/) was used for generating the documentation and make it available online, through two additional steps: 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-2.0.0/MANIFEST.in000066400000000000000000000003031421347431400161510ustar00rootroot00000000000000include *.md exclude Makefile include test/*.py include scripts/*.py include requirements.txt include requirements.development.txt include LICENSE.txt include ChangeLog.txt graft docs/build/html sparqlwrapper-2.0.0/Makefile000066400000000000000000000004301421347431400160540ustar00rootroot00000000000000# 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-2.0.0/README.rst000066400000000000000000000762441421347431400161230ustar00rootroot00000000000000.. image:: docs/source/SPARQLWrapper-250.png ======================================= SPARQL Endpoint interface to Python ======================================= |Build Status| |PyPi version| * About_ * `Installation & Distribution`_ * `How to use`_ * `SPARQL Endpoint Implementations`_ * `Development`_ About ===== **SPARQLWrapper** is a simple Python wrapper around a `SPARQL `_ service to remotely execute your queries. It helps by creating the query invocation and, optionally, converting 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 ========== You can use SPARQLWrapper either as a Python command line script or as a Python package. Command Line Script ------------------- To use as a command line script, you will need to install SPARQLWrapper and then a command line script called ``rqw`` (spaRQl Wrapper) will be available within the Python environment into which it is installed. run ``$ rql -h`` to see all the script's options. Python package -------------- Here are a series of examples of different queries executed via SPARQLWrapper as a python package. SELECT examples ^^^^^^^^^^^^^^^ Simple use of this module is as follows where a live SPARQL endpoint is given and the JSON return format is used: .. code-block:: python from SPARQLWrapper import SPARQLWrapper, JSON sparql = SPARQLWrapper( "http://vocabs.ardc.edu.au/repository/api/sparql/" "csiro_international-chronostratigraphic-chart_geologic-time-scale-2020" ) sparql.setReturnFormat(JSON) # gets the first 3 geological ages # from a Geological Timescale database, # via a SPARQL endpoint sparql.setQuery(""" PREFIX gts: SELECT * WHERE { ?a a gts:Age . } ORDER BY ?a LIMIT 3 """ ) try: ret = sparql.queryAndConvert() for r in ret["results"]["bindings"]: print(r) except Exception as e: print(e) This should print out something like this:: {'a': {'type': 'uri', 'value': 'http://resource.geosciml.org/classifier/ics/ischart/Aalenian'}} {'a': {'type': 'uri', 'value': 'http://resource.geosciml.org/classifier/ics/ischart/Aeronian'}} {'a': {'type': 'uri', 'value': 'http://resource.geosciml.org/classifier/ics/ischart/Albian'}} The above result is the response from the given endpoint, retrieved in JSON, and converted to a Python object, ``ret``, which is then iterated over and printed. ASK example ^^^^^^^^^^^ This query gets a boolean response from DBPedia's SPARQL endpoint: .. code-block:: 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()) You should see something like: .. code-block:: true CONSTRUCT example ^^^^^^^^^^^^^^^^^ CONSTRUCT queries return RDF, so ``queryAndConvert()`` here produces an RDFlib ``Graph`` object which is then serialized to the Turtle format for printing: .. code-block:: python from SPARQLWrapper import SPARQLWrapper sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX dbo: PREFIX sdo: CONSTRUCT { ?lang a sdo:Language ; sdo:alternateName ?iso6391Code . } WHERE { ?lang a dbo:Language ; dbo:iso6391Code ?iso6391Code . FILTER (STRLEN(?iso6391Code)=2) # to filter out non-valid values } LIMIT 3 """) results = sparql.queryAndConvert() print(results.serialize()) Results from this query should look something like this: .. code-block:: @prefix schema: . a schema:Language ; schema:alternateName "ar" . a schema:Language ; schema:alternateName "an" . a schema:Language ; schema:alternateName "es" . DESCRIBE example ^^^^^^^^^^^^^^^^ Like CONSTRUCT queries, DESCRIBE queries also produce RDF results, so this example produces an RDFlib ``Graph`` object which is then serialized into the JSON-LD format and printed: .. code-block:: python from SPARQLWrapper import SPARQLWrapper sparql = SPARQLWrapper("http://dbpedia.org/sparql") sparql.setQuery("DESCRIBE ") results = sparql.queryAndConvert() print(results.serialize(format="json-ld")) The result for this example is large but starts something like this: .. code-block:: [ { "@id": "http://dbpedia.org/resource/Mazonovo", "http://dbpedia.org/ontology/subdivision": [ { "@id": "http://dbpedia.org/resource/Asturias" } ], ... SPARQL UPDATE example ^^^^^^^^^^^^^^^^^^^^^ UPDATE queries write changes to a SPARQL endpoint, so we can't easily show a working example here. However, if ``https://example.org/sparql`` really was a working SPARQL endpoint that allowed updates, the following code might work: .. code-block:: python from SPARQLWrapper import SPARQLWrapper, POST, DIGEST sparql = SPARQLWrapper("https://example.org/sparql") sparql.setHTTPAuth(DIGEST) sparql.setCredentials("some-login", "some-password") sparql.setMethod(POST) sparql.setQuery(""" PREFIX dbp: PREFIX rdfs: WITH DELETE { dbo:Asturias rdfs:label "Asturies"@ast } """ ) results = sparql.query() print results.response.read() If the above code really worked, it would delete the triple ``dbo:Asturias rdfs:label "Asturies"@ast`` from the graph ``http://example.graph``. 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 even simpler. .. code-block:: python from SPARQLWrapper import SPARQLWrapper2 sparql = SPARQLWrapper2("http://dbpedia.org/sparql") sparql.setQuery(""" PREFIX dbp: PREFIX rdfs: SELECT ?label WHERE { dbp:Asturias rdfs:label ?label } LIMIT 3 """ ) for result in sparql.query().bindings: print(f"{result['label'].lang}, {result['label'].value}") The above should print out something like: .. code-block:: en, Asturias ar, أشتورية ca, Astúries Return formats -------------- The expected return formats differs per 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``. * 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: .. code-block:: python try : sparql.setReturnFormat(SPARQLWrapper.JSON) ret = sparql.query() d = ret.convert() except Exception as e: print(e) the value of ``d`` is a Python dictionary of the query result, based on the `SPARQL Query Results JSON Format `_. Partial interpretation of the results ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 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: .. code-block:: python from SPARQLWrapper import SPARQLWrapper2 sparql = SPARQLWrapper2("http://example.org/sparql") sparql.setQuery(""" SELECT ?subj ?prop WHERE { ?subj ?prop ?obj } """ ) 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(f"{binding['subj'].value}, {binding['subj'].type}") print(f"{binding['prop'].value}, {binding['prop'].type}") except Exception as e: print(e) 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: .. code-block:: python from SPARQLWrapper import SPARQLWrapper2 sparql = SPARQLWrapper2("http://example.org/sparql") sparql.setQuery(""" SELECT ?subj ?obj ?opt WHERE { ?subj ?obj . OPTIONAL { ?subj ?opt } } """ ) try: ret = sparql.query() print(ret.variables) # this is an array consisting of "subj", "obj", "opt" if ("subj", "prop", "opt") in ret: # there is at least one binding covering the optional "opt", too bindings = ret["subj", "obj", "opt"] # bindings is an array of dictionaries with the full bindings for b in bindings: subj = b["subj"].value o = b["obj"].value opt = b["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("subj") # an array of Value instances ... except Exception as e: print(e) 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 combinations 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. SPARQL Endpoint Implementations =============================== Introduction ------------ From `SPARQL 1.1 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 fact is that the **parameter key** for the choice of the **output format** is not defined. Virtuoso uses `format`, Fuseki uses `output`, rasqual seems to use `results`, etc... Also, in some cases HTTP Content Negotiation can/must be used. ClioPatria ---------- :Website: `The SWI-Prolog Semantic Web Server `_ :Documentation: Search 'sparql' in ``_. :Uses: Parameters **and** Content Negotiation. :Parameter key: ``format``. :Parameter value: MUST be one of these values: ``rdf+xml``, ``json``, ``csv``, ``application/sparql-results+xml`` or ``application/sparql-results+json``. OpenLink Virtuoso ----------------- :Website: `OpenLink Virtuoso `_ :Parameter key: ``format`` or ``output``. :JSON-LD (application/ld+json): supported (in CONSTRUCT and DESCRIBE). - 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 ------ :Website: `Fuseki `_ :Uses: Parameters **and** Content Negotiation. :Parameter key: ``format`` or ``output`` (`Fuseki 1 `_, `Fuseki 2 `_). :JSON-LD (application/ld+json): supported (in CONSTRUCT and DESCRIBE). - `Fuseki 1 - Short names for "output=" : "json", "xml", "sparql", "text", "csv", "tsv", "thrift" `_ - `Fuseki 2 - Short names for "output=" : "json", "xml", "sparql", "text", "csv", "tsv", "thrift" `_ - 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 Fuseki 2), "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, Fuseki 1 returns 200 instead of 400. Eclipse RDF4J ------------- :Website: `Eclipse RDF4J (formerly known as OpenRDF Sesame) `_ :Documentation: ``_, ``_ :Uses: Only content negotiation (no URL parameters). :Parameter: If an unexpected parameter is used, the server ignores it. :JSON-LD (application/ld+json): supported (in CONSTRUCT and DESCRIBE). - 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``) RASQAL ------ :Website: `RASQAL `_ :Documentation: ``_ :Parameter key: ``results``. :JSON-LD (application/ld+json): NOT supported. Uses roqet as RDF query utility (see ``_) 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). Marklogic --------- :Website: `Marklogic `_ :Uses: Only content negotiation (no URL parameters). :JSON-LD (application/ld+json): NOT supported. `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 (See ``_. 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 - ASK queries return a boolean (true or false). - CONSTRUCT or DESCRIBE - application/n-triples - application/rdf+json - application/rdf+xml - text/turtle - text/n3 - application/n-quads - application/trig AllegroGraph ------------ :Website: `AllegroGraph `_ :Documentation: ``_ :Uses: Only content negotiation (no URL parameters). :Parameter: 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. :JSON-LD (application/ld+json): NOT supported. - 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 4store ------ :Website: `4store `_ :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 (application/ld+json): 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) Blazegraph ---------- :Website: `Blazegraph (Formerly known as Bigdata) `_ & `NanoSparqlServer `_ :Documentation: ``_ :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. :JSON-LD (application/ld+json): 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 - 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") GraphDB ------- :Website: `GraphDB, formerly known as OWLIM (OWLIM-Lite, OWLIM-SE) `_ :Documentation: ``_ :Uses: Only content negotiation (no URL parameters). :Note: If the Accept value is not within the expected ones, the server returns a 406 "No acceptable file format found." :JSON-LD (application/ld+json): supported (in CONSTRUCT and DESCRIBE). - SELECT - 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 - 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 - 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 - 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 ------- :Website: `Stardog `_ :Documentation: ``_ (looks outdated) :Uses: Only content negotiation (no URL parameters). :Parameter key: If an unexpected parameter is used, the server ignores it. :JSON-LD (application/ld+json): supported (in CONSTRUCT and DESCRIBE). - 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 Development =========== Requirements ------------ The `RDFLib `_ package is used for RDF parsing. This package is imported in a lazy fashion, i.e. only when needed. 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 dev packages: ``pip install '.[dev]'`` - ``scripts``: some scripts to run the package against some SPARQL endpoints. - ``docs``: the documentation. Community --------- Community support is available through the RDFlib 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-2.0.0/SPARQLWrapper/000077500000000000000000000000001421347431400167625ustar00rootroot00000000000000sparqlwrapper-2.0.0/SPARQLWrapper/KeyCaseInsensitiveDict.py000066400000000000000000000025411421347431400237070ustar00rootroot00000000000000# -*- 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 `_ """ from typing import Dict, Mapping, TypeVar _V = TypeVar("_V") class KeyCaseInsensitiveDict(Dict[str, _V]): """ A simple implementation of a key case-insensitive dictionary """ def __init__(self, d: Mapping[str, _V]={}) -> None: """ :param dict d: The source dictionary. """ for k, v in d.items(): self[k] = v def __setitem__(self, key: str, value: _V) -> None: if hasattr(key, "lower"): key = key.lower() dict.__setitem__(self, key, value) def __getitem__(self, key: str) -> _V: if hasattr(key, "lower"): key = key.lower() return dict.__getitem__(self, key) def __delitem__(self, key: str) -> None: if hasattr(key, "lower"): key = key.lower() dict.__delitem__(self, key) sparqlwrapper-2.0.0/SPARQLWrapper/SPARQLExceptions.py000066400000000000000000000050431421347431400224020ustar00rootroot00000000000000# -*- 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 `_ """ from typing import Optional class SPARQLWrapperException(Exception): """ Base class for SPARQL Wrapper exceptions """ msg = "an exception has occurred" def __init__(self, response: Optional[bytes] = None): """ :param string response: The server response """ if response: formatted_msg = "%s: %s. \n\nResponse:\n%r" % ( 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 = "The endpoint returned the HTTP status code 500" 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 badly formed" class EndPointNotFound(SPARQLWrapperException): """ End Point Not Found exception. Usually HTTP response status code ``404``. """ msg = "It was not possible to connect to the given endpoint: check 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 to that endpoint 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-2.0.0/SPARQLWrapper/SmartWrapper.py000066400000000000000000000363051421347431400217720ustar00rootroot00000000000000# -*- 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. """ from typing import Any, Dict, List, Optional, Tuple, Union from SPARQLWrapper.Wrapper import JSON, SELECT, QueryResult from SPARQLWrapper.Wrapper import SPARQLWrapper as SW ###################################################################################### 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: str, binding: Dict[str, str]) -> None: """ :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) -> str: 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: QueryResult): """ :param retval: the query result. :type retval: :class:`QueryResult` """ self.fullResult = retval._convertJSON() self.head = self.fullResult["head"] self.variables: Optional[List[str]] = None try: self.variables = self.fullResult["head"]["vars"] except: pass self.bindings: List[Dict[str, Value]] = [] 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 = {} # type error: Item "None" of "Union[List[str], Any, None]" has no attribute "__iter__" (not iterable) for key in self.variables: # type: ignore [union-attr] 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: str) -> Optional[List[Value]]: """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: Union[str, List[str], Tuple[str]]) -> bool: """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 # type error: Unsupported right operand type for in ("Optional[List[str]]") if False in [k in self.variables for k in key]: # type: ignore [operator] 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: # type error: Unsupported right operand type for in ("Optional[List[str]]") if key not in self.variables: # type: ignore [operator] return False for b in self.bindings: if key in b: return True return False def __getitem__(self, key: Union[slice, str, List[str]]) -> List[Dict[str, Value]]: """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: Union[List[Any], Tuple[Any, ...]]) -> bool: if len(keys) == 0: return False for k in keys: # type error: Unsupported right operand type for in ("Optional[List[str]]") if ( not isinstance(k, str) or k not in self.variables # type: ignore [operator] ): return False return True def _nonSliceCase( key: Union[ str, List[Any], Tuple[Any], ] ) -> Union[List[Any], bool, Tuple[Any]]: # type error: Unsupported right operand type for in ("Optional[List[str]]") if isinstance(key, str) and key != "" and key in self.variables: # type: ignore[operator] # 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: Union[List[Any], bool, Tuple[Any]] = [] no_keys: Union[List[Any], bool, Tuple[Any]] = [] 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: List[Dict[str, Value]] = [] for b in self.bindings: # first check whether the 'yes' part is all there: # type error: Item "bool" of "Union[List[Any], bool, Tuple[Any]]" has no attribute "__iter__" (not iterable) if False in [k in b for k in yes_keys]: # type: ignore[union-attr] continue # type error: Item "bool" of "Union[List[Any], bool, Tuple[Any]]" has no attribute "__iter__" (not iterable) if True in [k in b for k in no_keys]: # type: ignore[union-attr] continue # if we got that far, we should 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) -> "Bindings": """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(SW): """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: str, defaultGraph: Optional[str] = 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: Optional[str]) -> None: """ 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) -> Union[Bindings, QueryResult]: # type: ignore[override] """ 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( # type: ignore[override] self, ) -> Union[Union[Bindings, QueryResult], QueryResult.ConvertResult]: """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-2.0.0/SPARQLWrapper/Wrapper.py000066400000000000000000001615761421347431400207740ustar00rootroot00000000000000# -*- 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 base64 import json import re import urllib.error import urllib.parse import urllib.request import warnings from http.client import HTTPResponse from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple, Union, cast from urllib.request import ( urlopen as urlopener, ) # don't change the name: tests override it from xml.dom.minidom import Document, parse from SPARQLWrapper import __agent__ if TYPE_CHECKING: from rdflib import Graph from .KeyCaseInsensitiveDict import KeyCaseInsensitiveDict from .SPARQLExceptions import ( EndPointInternalError, EndPointNotFound, QueryBadFormed, Unauthorized, URITooLong, ) # 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, JSONLD] # 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 + _RDF_JSONLD _SPARQL_PARAMS = ["query"] # 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 t he 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: str, updateEndpoint: Optional[str] = None, returnFormat: str = XML, defaultGraph: Optional[str] = None, agent: str = __agent__, ) -> None: """ 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: Optional[str] = None self.passwd: Optional[str] = None self.http_auth = BASIC self._defaultGraph = defaultGraph self.onlyConneg = False # Only Content Negotiation self.customHttpHeaders: Dict[str, str] = {} self.timeout: Optional[int] if returnFormat in _allowedFormats: self._defaultReturnFormat = returnFormat else: self._defaultReturnFormat = XML self.resetQuery() def resetQuery(self) -> None: """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: Dict[str, List[str]] = {} 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: str) -> None: """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 else: warnings.warn( "Ignore format '%s'; current instance supports: %s." % (format, ", ".join(_allowedFormats)), SyntaxWarning, ) def supportsReturnFormat(self, format: str) -> bool: """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: int) -> None: """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: bool) -> None: """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: str) -> None: """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: str) -> None: """ 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: str) -> None: """ 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: str, value: str) -> None: """ 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: str, value: str) -> bool: """ 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: str, value: str) -> bool: """ 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: str, httpHeaderValue: str) -> None: """ 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: str) -> bool: """ 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: str) -> bool: """ 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: Optional[str], passwd: Optional[str], realm: str = "SPARQL" ) -> None: """ 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: str) -> None: """ 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: Union[str, bytes]) -> None: """ 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 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: str) -> Optional[str]: """ 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()) # type error: Item "None" of "Optional[Match[str]]" has no attribute "group" r_queryType = ( self.pattern.search(query_for_queryType).group("queryType").upper() # type: ignore[union-attr] ) except AttributeError: warnings.warn( "not detected query type for query '%r'" % 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: str) -> None: """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) -> None: """Make :mod:`urllib2` use keep-alive. :raises ImportError: when could not be imported ``keepalive.HTTPHandler``. """ try: from keepalive import HTTPHandler # type: ignore[import] if urllib.request._opener and any( # type: ignore[attr-defined] isinstance(h, HTTPHandler) for h in urllib.request._opener.handlers # type: ignore[attr-defined] ): # already installed return keepalive_handler = HTTPHandler() opener = urllib.request.build_opener(keepalive_handler) urllib.request.install_opener(opener) except ImportError: warnings.warn( "keepalive support not available, so the execution of this method has no effect" ) def isSparqlUpdateRequest(self) -> bool: """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) -> bool: """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: str) -> str: """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: Optional[Tuple[str, str]] = None ) -> str: """ 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.parse.quote_plus(param.encode("UTF-8"), safe="/"), urllib.parse.quote_plus(value.encode("UTF-8"), safe="/"), ) for param, values in query_parameters.items() for value in values ) return "&".join(pairs) def _getAcceptHeader(self) -> str: """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) -> urllib.request.Request: """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 = urllib.request.Request( uri + "?" + self._getRequestEncodedParameters() ) request.add_header("Content-Type", "application/sparql-update") request.data = self.queryString.encode("UTF-8") else: # URL-encoded request = urllib.request.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 = urllib.request.Request( uri + "?" + self._getRequestEncodedParameters() ) request.add_header("Content-Type", "application/sparql-query") request.data = self.queryString.encode("UTF-8") else: # URL-encoded request = urllib.request.Request(uri) request.add_header( "Content-Type", "application/x-www-form-urlencoded" ) request.data = self._getRequestEncodedParameters( ("query", self.queryString) ).encode("ascii") else: # GET request = urllib.request.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 = urllib.request.HTTPPasswordMgr() pwd_mgr.add_password(realm, uri, self.user, self.passwd) opener = urllib.request.build_opener() opener.add_handler(urllib.request.HTTPDigestAuthHandler(pwd_mgr)) urllib.request.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) -> Tuple[HTTPResponse, str]: """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 urllib.error.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) -> "QueryResult": """ 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) -> "QueryResult.ConvertResult": """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) -> str: """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 """ ConvertResult = Union[bytes, str, Dict[Any, Any], "Graph", Document, None] def __init__(self, result: Union[HTTPResponse, Tuple[HTTPResponse, str]]) -> None: """ :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) -> str: """Return the URL of the original call. :return: URL of the original call. :rtype: string """ return self.response.geturl() def info(self) -> KeyCaseInsensitiveDict[str]: """Return the meta-information of the HTTP result. :return: meta-information of the HTTP result. :rtype: dict """ return KeyCaseInsensitiveDict(dict(self.response.info())) def __iter__(self) -> Iterator[bytes]: """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) -> bytes: """Method for the standard iterator.""" return next(self.response) def _convertJSON(self) -> Dict[Any, Any]: """ 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 """ json_str = json.loads(self.response.read().decode("utf-8")) if isinstance(json_str, dict): return json_str else: raise TypeError(type(json_str)) def _convertXML(self) -> Document: """ 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` """ doc = parse(self.response) rdoc = cast(Document, doc) return rdoc def _convertRDF(self) -> "Graph": """ 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` """ from rdflib import ConjunctiveGraph retval = ConjunctiveGraph() retval.parse(self.response, format="xml") # type: ignore[no-untyped-call] return retval def _convertN3(self) -> bytes: """ 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) -> bytes: """ 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) -> bytes: """ 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) -> "Graph": """ 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.parse(self.response, format="json-ld") # type: ignore[no-untyped-call] return retval def convert(self) -> ConvertResult: """ 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: str, expected: List[str]) -> bool: """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: str, allowed: List[str], mime: str, requested: str ) -> None: """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) -> Optional[str]: """ 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: str, expected: List[str]) -> bool: """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: Optional[int] = None) -> 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: int """ # 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 None 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: Dict[Any, Any], minWidth: int = 2 ) -> List[int]: width: List[int] = [] 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: Dict[str, str]) -> str: 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) -> str: """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.geturl() str_code = self.response.getcode() 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-2.0.0/SPARQLWrapper/__init__.py000066400000000000000000000022751421347431400211010ustar00rootroot00000000000000# -*- coding: utf8 -*- """ **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__ = "2.0.0" """The version of SPARQLWrapper""" __agent__: str = f"sparqlwrapper {__version__} (rdflib.github.io/sparqlwrapper)" from .SmartWrapper import SPARQLWrapper2 from .sparql_dataframe import get_sparql_dataframe from .Wrapper import ( ASK, BASIC, CONSTRUCT, CSV, DELETE, DESCRIBE, DIGEST, GET, INSERT, JSON, JSONLD, N3, POST, POSTDIRECTLY, RDF, RDFXML, SELECT, TSV, TURTLE, URLENCODED, XML, QueryResult, SPARQLWrapper, ) __all__ = [ "SPARQLWrapper2", "get_sparql_dataframe", "ASK", "BASIC", "CONSTRUCT", "CSV", "DELETE", "DESCRIBE", "DIGEST", "GET", "INSERT", "JSON", "JSONLD", "N3", "POST", "POSTDIRECTLY", "RDF", "RDFXML", "SELECT", "TSV", "TURTLE", "URLENCODED", "XML", "QueryResult", "SPARQLWrapper", ] sparqlwrapper-2.0.0/SPARQLWrapper/main.py000066400000000000000000000103521421347431400202610ustar00rootroot00000000000000#!/usr/bin/env python # -*- coding: utf-8 -*- import argparse import json import os import shutil import sys import xml from typing import List, Optional import rdflib from . import __version__ from .Wrapper import SPARQLWrapper, _allowedAuth, _allowedFormats, _allowedRequests class SPARQLWrapperFormatter( argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter ): pass def check_file(v: str) -> str: if os.path.isfile(v): return v elif v == "-": return "-" # stdin else: raise argparse.ArgumentTypeError("file '%s' is not found" % v) def choicesDescriptions() -> str: d = "\n - ".join(["allowed FORMAT:"] + _allowedFormats) d += "\n - ".join(["\n\nallowed METHOD:"] + _allowedRequests) d += "\n - ".join(["\n\nallowed AUTH:"] + _allowedAuth) return d def parse_args(test: Optional[List[str]] = None) -> argparse.Namespace: """Parse arguments.""" parser = argparse.ArgumentParser( prog="rqw", formatter_class=( lambda prog: SPARQLWrapperFormatter( prog, **{ "width": shutil.get_terminal_size(fallback=(120, 50)).columns, "max_help_position": 30, }, ) ), description="sparqlwrapper CLI", epilog=choicesDescriptions(), ) input_group = parser.add_mutually_exclusive_group(required=True) input_group.add_argument( "-f", "--file", metavar="FILE", type=check_file, help="query with sparql file (stdin: -)", ) input_group.add_argument("-Q", "--query", metavar="QUERY", help="query with string") parser.add_argument( "-F", "--format", default="json", metavar="FORMAT", choices=_allowedFormats, help="response format", ) parser.add_argument( "-e", "--endpoint", metavar="URI", help="sparql endpoint", default="http://dbpedia.org/sparql", ) parser.add_argument( "-m", "--method", metavar="METHOD", choices=_allowedRequests, help="request method", ) parser.add_argument( "-a", "--auth", metavar="AUTH", choices=_allowedAuth, help="HTTP auth" ) parser.add_argument( "-u", "--username", metavar="ID", default="guest", help="username for auth" ) parser.add_argument( "-p", "--password", metavar="PW", default="", help="password for auth" ) parser.add_argument("-q", "--quiet", action="store_true", help="supress warnings") parser.add_argument( "-V", "--version", action="version", version="%(prog)s {}".format(__version__) ) if test is None: return parser.parse_args() else: return parser.parse_args(test) def main(test: Optional[List[str]] = None) -> None: args = parse_args(test) if args.quiet: import warnings warnings.filterwarnings("ignore") q = "" if args.query is not None: q = args.query elif args.file == "-": q = sys.stdin.read() else: q = open(args.file, "r").read() sparql = SPARQLWrapper( args.endpoint, agent=( "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/96.0.4664.110 Safari/537.36" ), ) if args.auth is not None: sparql.setHTTPAuth(args.auth) sparql.setCredentials(args.username, args.password) if args.method is not None: sparql.setMethod(args.method) sparql.setQuery(q) sparql.setReturnFormat(args.format) results = sparql.query().convert() if isinstance(results, dict): # "json" print(json.dumps(results, indent=4)) elif isinstance(results, xml.dom.minidom.Document): # "xml" print(results.toxml()) elif isinstance(results, bytes): # "csv", "tsv", "turtle", "n3" print(results.decode("utf-8")) elif isinstance(results, rdflib.graph.ConjunctiveGraph): # "rdf" print(results.serialize()) else: # unknown type raise TypeError(f"Unsupported result of type {type(results)}: {results!r}") if __name__ == "__main__": main() sparqlwrapper-2.0.0/SPARQLWrapper/py.typed000066400000000000000000000000001421347431400204470ustar00rootroot00000000000000sparqlwrapper-2.0.0/SPARQLWrapper/sparql_dataframe.py000066400000000000000000000045751421347431400226550ustar00rootroot00000000000000""" Query a SPARQL endpoint and return results as a Pandas dataframe. """ import io from typing import TYPE_CHECKING, Any, Dict, List, Union from SPARQLWrapper.SmartWrapper import Bindings, SPARQLWrapper2, Value from SPARQLWrapper.Wrapper import CSV, SELECT, SPARQLWrapper if TYPE_CHECKING: import pandas as pd class QueryException(Exception): pass def get_sparql_dataframe_orig( endpoint: str, query: Union[str, bytes] ) -> "pd.DataFrame": """copy paste from: https://github.com/lawlesst/sparql-dataframe""" # pandas inside to avoid requiring it import pandas as pd sparql = SPARQLWrapper(endpoint) sparql.setQuery(query) if sparql.queryType != SELECT: raise QueryException("Only SPARQL SELECT queries are supported.") sparql.setReturnFormat(CSV) results = sparql.query().convert() if isinstance(results, bytes): _csv = io.StringIO(results.decode("utf-8")) return pd.read_csv(_csv, sep=",") else: raise TypeError(type(results)) def get_sparql_typed_dict( endpoint: str, query: Union[str, bytes] ) -> List[Dict[str, Value]]: """modified from: https://github.com/lawlesst/sparql-dataframe""" # pandas inside to avoid requiring it import pandas as pd # rdflib in here because there is some meta stuff in the setup.py and Travis fails because rdflib is installed later import rdflib.term sparql = SPARQLWrapper2(endpoint) sparql.setQuery(query) if sparql.queryType != SELECT: raise QueryException("Only SPARQL SELECT queries are supported.") # sparql.setReturnFormat(JSON) results = sparql.query() if not isinstance(results, Bindings): raise TypeError(type(results)) # consider perf hacking later, probably slow # convert list of dicts to python types d = [] for x in results.bindings: row = {} for k in x: v = x[k] vv = rdflib.term.Literal(v.value, datatype=v.datatype).toPython() # type: ignore[no-untyped-call] row[k] = vv d.append(row) return d def get_sparql_dataframe(endpoint: str, query: Union[str, bytes]) -> "pd.DataFrame": # pandas inside to avoid requiring it import pandas as pd d = get_sparql_typed_dict(endpoint, query) # TODO: will nan fill somehow, make more strict if there is way of getting the nan types from rdflib df = pd.DataFrame(d) return df sparqlwrapper-2.0.0/docs/000077500000000000000000000000001421347431400153475ustar00rootroot00000000000000sparqlwrapper-2.0.0/docs/Makefile000066400000000000000000000013621421347431400170110ustar00rootroot00000000000000# 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-2.0.0/docs/make.bat000066400000000000000000000013641421347431400167600ustar00rootroot00000000000000@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-2.0.0/docs/requirements.docs.txt000066400000000000000000000000321421347431400215550ustar00rootroot00000000000000sphinx<5 sphinx-rtd-theme sparqlwrapper-2.0.0/docs/source/000077500000000000000000000000001421347431400166475ustar00rootroot00000000000000sparqlwrapper-2.0.0/docs/source/SPARQLWrapper-250.png000066400000000000000000000306251421347431400222320ustar00rootroot00000000000000PNG  IHDRq&zTXtRaw profile type exifxڭWrE1lDϠk#")RzWO dU&1 Kf?9XSl[lCϟ绳{z}~ݔR{x~u}~CMqk_a(u4-׶~=o.f ˅.T~N&%|?;_Wp<m+.}+ruN[Tz~vc6+6D#UܯWN0vKsr&K~wo~ _Lha& ycqw F?__:GeYzP/Ww^1M7<@ seݎg{m`h~qe D̝X dfsı}~LUz>57w?//$" iS[}bJ)jjcN9璅SK*RK+kZkdZnZLcgađFeFό3<ˬ; 0+jo)wy]wPk'xɧz?gͽot]y/6$匌xQ(hbʜrf&[2)9)cd0nq?r_4o9}׼}/>ݨ.$ d`מb-G{HD9VɶR`X?ep ׶b#$cVXD'Eb׳.E2)6K7-I".t-rQ;ig߳1g"[m)H򱮕"xv6q!YHl]52d,!s 6ՒF Rsqv!gx66-I6 eMڭb^[ }cQ˱Ǯ)6Amj үSDl2H~082FX|q<E^t 9E!Ee)b5grO6p(qd5po}ke!y?Q >e%kmjB.R>,f*hqqѝ5)[}"c-P߇=Hn:`h֗~Cn ~$|{~_I-R96J~^)k]f^\THR/l}J~M[|̈КR>֦aߐ ?r:& . dv8ga3 K; ?IS`C= _%a':C}k v\cKن7cATxnG>`S PSEthJb׸jdm|l u!fu\葨cphdB%u;.WM@rl)U-ʝ.v_\VNKJq ((~\6]`ރ?+L.3B9A.nV߃#yOIh^$&25d4# huW7lׁM\K%`s>RKo7.Q>0!]t7PcZ ,/BhbEOvmRt%Ҽ_'Gb>%ZhxJ8U: PJ cC$!4$gƄ /t(&nxTK4٘/s!qn08A-x@&z,R=@ng~;=rBl{E$9(VWqa(1>Z3wl!ɵo$‘XO+UU)4lk6˓kpЄC8rAєe!ϼ" 9bў-Y1YGQ1i|}g bm#+Kإш(HG{q|@Q$2ZM;&9l&m\=Iq8py0: Yy>؄(?!zNF=]}D3!bEh$2d!RZh]O %,I_g6 aT8 e4q(䠓FKEV]JwZh写!krlPIB305S`_W6(]0 zrHfՐeԙ(W`v밬IU"}"јChN6nCgÊNf"f8H[8~l-&"1"fbn^FSw .T:f$!q}@֎e9Ec>ĨSZN@ )>&f?;vȪ(g>_fRX+^"rQn>laoI x>256BG[XAloN9uv" ; b>a=y8Bx:KVz6J&i(Tw#FPB0{L 1kJ$m2KЛEAdQ'U-Q& Aȁu̓FhhG>j :IYَjqa, 3e3 (B_A4/&"f/d!w0 i&1#ݙ&AepSDbI(z>!97דAB ^=$N\vPw0p;B!f2GEK-P qTttv`T7"ױK`8v*;I'fe"4_P^ώ"υCL/!1Gm"5 Ju넁i :db#y ',i+Z;SnUPd2Lmd>zt`rQrr5Z=ᯚkD1,t oJ&X{YcFdԓ/q%) A:\.n$n{6G2f#1p) FZ!VSl87zcVPH#~[2:VP1}$Zfsh}j}5T, A j{ :8Dx*x4RxpDV$K ia]W!a"<-C0 C;r큫H33^d$HiTDTQ@BF&:]φ' *;Ń 9R8FIAyѶX@"'%-il/sEh 65.[vT%P| H5}GE-D(RH )拎e.:v̄qPA/q˥8mrz=g:oF"…>ljo)`yEi!NGQJa! VMϞ o(yjѤvB:--g3jZ"B=|w=}t-ٕG,ϡc_:BiV.#)|O.z'aq~㻉Yi;:Z6EωY` ;a22:vCxLClۙ:qapTG0XjiCu.4##XԌ/u.vJu>6?0MAw$28Y-t)aC <-ElETՀ7;4<.dFY"[ Ut_^Oͅ 0v>_rJ!lֳz^z1rLI9~9>E#CT^^g#Ppv@g@SMPԪJfrq N[w6o9BzJst =zmogoE ǡbo{ótleҷ)ka֋[XR5C9Y+[~N~|4DcAl|sM?["NMM{?'C?D<'./k|n_旉k|_ԶI/k{ ѷwZg<}B^Џ>UNRh'J/qnߣR!% f+ZYZApcfP+?߈ks%phPSh7̍*̿!,=~/$f 9h.ET:OZw3xZ=)OD{5#n*2y:pGcN[UaWM"AY):wzs~1v JJCy6=$[*y|?*K˸KRA:>`ܛ2[u?o9N1y;=錩>q>zyz/憳Uu6/9*hzWc忝,ܼ?l;|Uڿ[|/mްom f*yu;5]/ p׉2<0O < `q:uu6Kń =D Fg1E\A~,Y-zGtl! %dapabӦ@&8Z6Dm塳plXq\ 9 ==؆ {R1H@w[`x=cp>oP0ns1=9qUq!7W v:1"YG5>~p k?'A+2 n@."~JйuǙGuKŧ*|m t J}5W9[-iCCPICC profilex}=H@߶8AD!Cu *U(BP+`r4iHR\ׂ?Ug]\AIEJ.)ޗTk P5H'B6*^4$fswq]Q&|, xxj9GYIRωG #e8̨IGbJJ̓JzY(R =|W/l2Ia0d=1{ ecD1Jq8pp0`y@_ 'v[FsC` ,_ ԄM ]%tF{RLन;-SX53k4g0tG7RPL{oD3 9.G jDR*>m`HAŕjKA}@E~X&A JcKAMY,o G?vC5s"z%sњM "?Aʕ( )sYd5G0Xs7i5ooV5tclP[%[ScPu%_ g e5ҹ=b-@,孯QonTOvlT^kI竂fl3!gXZl}C]Dvk)[O>[c?]y`ݻj 4jLG(.ݶ(pzHx^Hk<ޡЛ׍s!Mَ; C6Pc;.qRQ߱nՅ(yq/MܣqG#j5pB)aiD}Z %$pZۛ#?nUHB-H!(PX{%n">_<{C')նVO5N{l^4.T@ {)ow(8?exnSDvߍ)ʢvDw,v^Ӗˁ=R{5m~5kku?Q\3wVD1'%ڮhuxV)u(%"+؅LA[D)e4ӛҙ1B6汼Kz|%r!0UӬPz!v;)wKVevpy?nQh[,,<{|>'t|q3ۆRPMxnRBd~J ˀ#[ ,ߩ>!XNXlo4Yw6IR}K!R"9{MdFj\h@0q߭0'8`ރAG)aJ}m`Ygj.;KvTS{˺4?o㡚QCMA: ͡OhNo;ՃOu ǁ4OͶ {A8[s%jt""ߝ`yfBm嶂RpJ'e|f*_ ,Ҝ:ͨDna3P/MG_ $]{)Irќj.-{;w[[.6[s7[BO0FkЦqScu!k|&)>\0mKxˇsQZo),"R͙^[2]R6=[KD. ^5ncZm"-ƀYsl@۔2\ь Rjʶbfi$<_9wiQ[&pT}IҤmn]G]o~?Ȑ=[Rg?XE S(7u>W*Jы4_G]ݹ BR@9D&|woЭ!mf%^HeUH39۽cuzx20=8̎+DLʓi'UǓSW-g䗸j'emN$(- !0M͂[h=sR83^Zg\L`-XZp5.<=I-Ȕ ́goοf}3UP#46Nz2TV=~,Ny{]ðx֌Kxh ֣~}XhbPl7~G_I$4xOC-v ?Z'va^@*QnB6΅;JJICȷ\E9EJ 8`OU1m.^S+DIChː Z}`I%Wj-)Gs*m}]lxlGn- Yچ8R|;^ :k#זmꔓ5o%VDF4َ}cwM/7tj7NDSLMWk&fUnY3)m-MŦ DZ`C5E}{q'qC7[VtXC(~fŝ{wfTQ963o=Omb&O-- /%2ޚ2) E/uAJ?5 ,q:$,+(nwρŁ``(f_Pl{/W\u3W8OU$tO",Dqoy,rQ`{W G(EoP fuFchU)o9چ < 5:q^uׅ~.%m}xԲP,5WmmL~ha`$wV{'t lC0?&oZk [%`Bш_4ΠwDgm=^m" peͶ>EdwP(?yط:+e%URF.ij}"Kv~`#G>?S8>KƓЇJU@2BmuP0pp'i (x-p+}DvQ)| E 56-`YP^dxĔX]y,m-R)YDߙ8+|EA/K!W Bwo䄗I»@8ǎ<W';붦;!+i ~Fߔo5os>U88Fξ[SrtjbKGDC pHYs B(xtIME q IDATxy|T?IB}f@**"mPK& cWي,G آ A[[jULHXͽAk¹3d~{9s@DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDYKr>k ͼPV2;z;h^Q`@ GjH_0>ѤV` 6vljL`.i`!""OhQǹƜbDND'_]-l-n_)|}CL@?uNq_k9_Dp@Ӵ ʖp'" 9cE#E#(R4jXGxˊ2Q ;Szs7uܵa'PY1Qg{H|hgUxeƳ1)(cc73z)-W~s;DDQ9Wgz0y /Ї-,/X4&oq|[IADDi *$Mʬ>{ʤ ""?RڞP`6yJ>w[DD䛓9+EGLʔ9KwDDd-.1@s_L)T:cL ""T{Ss7;eD~} G3)F ,*I%*ء ULp8MЅFLb6%"ö v'gݗ5}oW]t2\3a0Q~ƊgUcuvR+xsl>b΄oхm;Ɲcsw""ꐀ>b\heg[yqϞP UDDE5 M f,ߘtW\q+3}*+/?(R^P *~ޝ]t]F_zQ6:_ѲeIjҨ69e'ouAw?%uo8eqPs/ҹ+u_ fQ+00 +.8-׭%su&>Q뱷)pQ'}WJf尽ғ*Ffl@ͅ?3s/y(7L0e܋gg]44DD#mŷΜuf:ܦg{ȸ?zo.P = f~ڜ߭p8}ۈТFU=I~ǟ|F 4?Ę_cɭgjч ()h(> ă'y;)NvNNVPxwV)ˀN'EGrnH@r}B|DpA$KT6 q[:};S( mELŮzR z%(TK#B%UAVի=znL8 ж|8^/4CFn)'P h_R`tBD8boVMkK DpyPϋ[PI #%V[qw{ s30Y@ !Ty3ۭ5]%oKNP(W 6B@:}Pq Ŧj#gt9|R@waj6NvrƶuFe '0XcV8@MUHS7Tpl'%HUh*~?!ҖSUIEoE*F4JVBc5wW0ݠCP7?T 4KOy5fdOU1 h p'T2oAՌehy잼(N_54McV{ݺŌM \d=qJP:-䙇x#T-fvD7@J*T})X2o '\ng-{ oyB 2ED ;%LL9APjqu(=c=ȆpItV9}cGx<9K1ȠZ|2K?yfKQ}2T2Y=J#D:1F'߲nGN:O'XZui/*r+{2ԏx.Sρ#&EOx_?Bܔv7)= HUN<)sTt79* rQ RvgA'E^˞G/խk-3@3nM[|҄78]]Y*dNNwS;0zb1FD{*R.Rflu`y@~~ECfKCf4-i:'ۮvOa>|sgW}M.bl̈́{Q\ N.0Y `\ :Kn{}aFWSWx3vڊH`1(-U +9}e#y,knmg^}M.]f{fՖ%>v9-3OgX @m^Q=ϽOR([velT<ۆ:4q1Vo5z\&=dҫzڿ=l1;-="¡K١сٝEe۾KyM&TC(n\:}VطBл=Т`j˯Kh"xc?7\-Q/[1C8te7ԥEZ?_&f{ܽ><m\ ɪܐDZ˝zΙlVg> ڏﵿG˥ nw ,,B xw2=,iD꧈rqYл<'MCTள|N4{3tw] `EE䏱nwI&r~UyJ/D>+w{5Aq:q No3CQ1=E[&ݺ* YtduƗwl^Wԫ2i2.9>8*0-ڶb5 i= :`" 1A\npOCG|tMeN8㣽vqP BǺ/t3ھ`+TU=j: B8T(èn{: (h)>>4|*¯mj>G~ 8hUWK5(Ubc@OӕW&zCUDN,I:\?[Z$ Ms"sbX/a:7:9^]1Ԩ>9=]-4j$D'>wU}u86:l5zxu@T ]{ou>^Zn~\)u ix|1 WyaJ ty*؍=ӱ7+,=tXջfzO*pl0%ntf}DUN$`t^Т&laB5J޸`Dg5]mқVj'Ecx[ Wb}K}5Wj=MUoܵkZ D TM =Yc,gpnRGK舁a7#=kЩ{K5q\5ͷs_,f}WNK]c121EB _` D7K T}!kqgP+}첸#T[GP=յa֯DQ+yzHYՇt-5ԥE0f@V_ݪʸF/S0QRC$&/8kߴʟ!tۣ6@ d~Q44jUluuKoTfp8LS9^4zvoy7-h " S_s*2q" 'f\J;kjk[em-j޺OZo[5MT[|+un-+LoĖ@Q@m:rM.?f?+=|SsE3 muJmVx ΰK* G{z:8K\yNAk$AUר/nr2 dǁOA="DNՑ*v * yOf[Sf>5>G9}33z Vz$|.-X<gFDf: #? TE'(C+0"VKDy~ʤt`I0U$[R`A}u{=`M&Ї{Q_P] 0;#cv-z\(Q_Pem}6/6fI* k+MzK,PtLQ TPIuQ<&۹, H&#m^*]L;2?V)xɀ܍1^N(G[A-xtda)+T3Z bp\siN#pid'|]>[]лb5j## DJ 4uҩ8"X.ޖa/J]:nJad{gmMW[k"غvLyoi EiVvT4k23wm5jkj#ߌD.mCo9[ 1tE]+)(~/8.VC?Hۺ7LenwLE|>4QN#¸Z>62g2~ xf@멎BQTNb#zOس]Y{xIbu+^M D'=S=5]Jc<jjhݐJ'tCǼCHR1w YM|4m-@[xʰ˝=Zv#m'`n<n[w{ it1&֧mGŽ%-OrsѓRv PSDAzl߶!:hoS`A3Y  'z'_ ce3't;K{} uTlayy| 5ҁiבCx;V[)ge puI{-&x_,4F?x “条·bgpoUOA 5;ṋͫ1 :ATj+fu{B=gVa|.fytꖖۻmB~sBO O}dWN[Qp=%:}QW٭p6,]S2gy8[nYU-U;O6[WM.e f&@}қfN/7-HE.p<`j<NrEsu%[W~w^h Zwq,*x%:B}Mˮztj&3RS?e޹;9:lVz?ot8^ #eGq$f;4C>IÒ[6KL߱l|Y7En u5;s"wPؼo 6 fHaC5lw`ɼ))q`z$nBF8 _~%Us歪+Gq_=jZ3ĺ[HtuON<; x1 ZrR֚+mTS8wǞC4EIDATgl٩`v[8a3Z{~P\`Yt ~\ 6mfV{Չ9<E1e oGܫïZn?`RK#otf&F"`–-7M WuR  Zqz:N@GxQy~7f4bOŻ,wer^KUgTiKT'f[n ךu/bͺeTuwa4:pAօK}ׇ[M]󰟉D22_g}@7g7G[k%SNPhRHNe/3t~.N8dZ"_8?Cn3#.֕ؾ/Thtĥ}G}nk]~HKm~7:Vg}fyK82?`X/)GyuKoyKs=/m$B߲YpIta?P]4 N?!frr8dfD- ,i/[n8C-H0 L FDSV@lIdq1k>w @j"HSC'VSwa\eP{36%fTEFt5yOp-7tdٹuWծ#lyn+K+CxPi{xߺ tX#m4?2o}29s});qPIt>=`/M2b"n?&>w}=R}-4%U#RuV)VVtQ_CM,1VRYwXUW7}%PɼEaQޡnotKfx%ste_>H0uW7kZ肔LoH`׳ ˡyT/C*f:$X,UhI4"T-)9zκ}WdҹY~ӮPIt%"| r%CZaCeIŘ%+å>8Z"ݸC%̀,Dڛ[5Jà<`h2Ֆ75[󙔳 :Y|}pq< 'OB%L\bu;Ȼew3ȋz:N{ (GưYh1ˀ(;>ڻaedw\=qquT&23X\KD$YtQ|y_֦Piex]DS ^#S5FE@PXsh_h>6.RE͞&u-TK5Y(ި(E}Phg TeEz{KPqj$1C 8"V95/- T}~gmk,9:N]5mUs2?br!j"34? gzI|>{b][Z>`k{]rkw^S}ؒL^2x.XG#S6\L\IXmP 1@Gu:٦d'i.}8/SfA1K&' :lYbPUCf +j.xˊߦL%j#w`3&ϩ+|-8uqdg1.9lxi3s]:TڊN@vL*4:/-Ò$nk۩f,ߘ""R&:? 3^UKaJ]:h\l|޾薷2zbo+e%Fc{hi MViWuORHMՌ~CpV@_itKC q^Ҫ&SqѴؒU0 8WTXm"@> /puWy\c>LhRȬ#H*Kn{}myiN="c̐XmZ) QMɠQ, T}gm$`8c^q@.r{ĢP0.Vp.R'9T і dZ׺M``1E>9* }B eu5Հ,N/@t" n*sý}u2X:EQ%FM o-Q!0؇i]x[Txڶaǖ Mc+PڱLS'MD\c!z.p6 T[Q=冲Na4ŞXכ 87n=ly7jT`]Зz,%o^3$pFkt[gmKNT1| <;~v] l*6/%6T#"s&xjh(+_ڗ:mP4hh&:s8|yxN;UYizw{msJD3d܂n{ !g|7vK[ G."?ǯwpb5+ ЉHxRȣP hnI) V`Ĝ &9Q>9:u1;߼#VoTE4$RT:L""@T7/[DDDĀNDDD DDD DDDĀNDDD DDDĀNDDĀNDDD]TN,##x(8nnKtQN55&ݏ]DDDYЉЉЉR($ ""JH3۠8` DDD]#; WyP 3e-FL}5k <ޡDDC^1`oqNYs?DD#bF2n{ʚo t6_"" ߓa{7JܛASЁDD\vuG36;=+&"r9aYK2?F$t|jU3'x(lN'|U;-qJ-DDv% yk5ˁN rKoADDz& ^:`7ec>zBߨ%ej+W*"9eń ;@FnHx@Q9N7p}`ak|#ta[SFy*XODDU*$}w-''j6%;ugxgE0uc ".Ip3l|79%|sʚ!Љ({xlpz.' tNY놭bGz3l퍉aV%"C)mt]汵9؅Gtw8۞jS i2.aJS`V[*j@Qn7x ܚ""jS IaEo# &vm9wTp ejUR ! [ 3a@'"N㜲@fJ, [x€NDDǰ_LD -?ů܉(a1uX暦Љ(ϻ3BV|R`YvQr7 ч/Y1ɩlQJmsf8AuX,*w)_01AMFpR50S_xƀNDDbc8cj(-qBHN~qc[훇gxX /QfdOuv_;}'P+di-oP t SPARQL Editable font Outlined Font sparqlwrapper-2.0.0/docs/source/_templates/000077500000000000000000000000001421347431400210045ustar00rootroot00000000000000sparqlwrapper-2.0.0/docs/source/_templates/globaltocindex.html000066400000000000000000000004451421347431400246730ustar00rootroot00000000000000{# 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-2.0.0/docs/source/_templates/localtocindex.html000066400000000000000000000006141421347431400245230ustar00rootroot00000000000000{# 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-2.0.0/docs/source/_templates/sidebarhelp.html000066400000000000000000000002541421347431400241550ustar00rootroot00000000000000

Need help?

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

sparqlwrapper-2.0.0/docs/source/changelog.rst000066400000000000000000000000431421347431400213250ustar00rootroot00000000000000 .. include:: ../../ChangeLog.txt sparqlwrapper-2.0.0/docs/source/conf.py000066400000000000000000000154341421347431400201550ustar00rootroot00000000000000# -*- 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 = 'SPARQLWrapper' copyright = '2019, `W3C® SOFTWARE NOTICE AND LICENSE `_' author = 'Ivan Herman' author = 'Sergio Fernández' author = 'Carlos Tejo Alonso' author = '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 html_logo = "SPARQLWrapper-250.png" # -- 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', 'SPARQLWrapper Documentation', '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', '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', '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-2.0.0/docs/source/docs/000077500000000000000000000000001421347431400175775ustar00rootroot00000000000000sparqlwrapper-2.0.0/docs/source/docs/source/000077500000000000000000000000001421347431400210775ustar00rootroot00000000000000sparqlwrapper-2.0.0/docs/source/docs/source/SPARQLWrapper-250.png000077700000000000000000000000001421347431400304522../../SPARQLWrapper-250.pngustar00rootroot00000000000000sparqlwrapper-2.0.0/docs/source/index.rst000066400000000000000000000016371421347431400205170ustar00rootroot00000000000000======================================= 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-2.0.0/docs/source/main.rst000066400000000000000000000000401421347431400203170ustar00rootroot00000000000000 .. include:: ../../README.rst sparqlwrapper-2.0.0/docs/source/modules.rst000066400000000000000000000002751421347431400210550ustar00rootroot00000000000000SPARQLWrapper package ===================== .. toctree:: SPARQLWrapper.Wrapper SPARQLWrapper.SmartWrapper SPARQLWrapper.SPARQLExceptions SPARQLWrapper.KeyCaseInsensitiveDict sparqlwrapper-2.0.0/pyproject.toml000066400000000000000000000001321421347431400173270ustar00rootroot00000000000000[build-system] requires = ["wheel", "setuptools"] build-backend = "setuptools.build_meta" sparqlwrapper-2.0.0/requirements.development.txt000066400000000000000000000002041421347431400222200ustar00rootroot00000000000000setuptools>=3.7.1 mypy>=0.931 pandas-stubs>=1.2.0.48 -r requirements.optional.txt -r requirements.txt -r docs/requirements.docs.txt sparqlwrapper-2.0.0/requirements.optional.txt000066400000000000000000000000751421347431400215310ustar00rootroot00000000000000# To use sparql_dataframe: pandas>=1.3.5 -r requirements.txt sparqlwrapper-2.0.0/requirements.txt000066400000000000000000000000161421347431400177000ustar00rootroot00000000000000rdflib>=6.1.1 sparqlwrapper-2.0.0/scripts/000077500000000000000000000000001421347431400161065ustar00rootroot00000000000000sparqlwrapper-2.0.0/scripts/example-ask.py000066400000000000000000000014141421347431400206670ustar00rootroot00000000000000#!/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-2.0.0/scripts/example-construct.py000066400000000000000000000023541421347431400221410ustar00rootroot00000000000000#!/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-2.0.0/scripts/example-dbpedia.py000066400000000000000000000014101421347431400214750ustar00rootroot00000000000000#!/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-2.0.0/scripts/example-delete.py000066400000000000000000000006111421347431400213510ustar00rootroot00000000000000from 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-2.0.0/scripts/example-describe.py000066400000000000000000000016361421347431400216770ustar00rootroot00000000000000from 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-2.0.0/scripts/example-federated.py000066400000000000000000000014721421347431400220400ustar00rootroot00000000000000#!/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-2.0.0/scripts/example-insert-using-rdflib.py000066400000000000000000000017441421347431400240060ustar00rootroot00000000000000from 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-2.0.0/scripts/example-insert.py000066400000000000000000000006121421347431400214140ustar00rootroot00000000000000from 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-2.0.0/scripts/example-optional.py000066400000000000000000000013571421347431400217440ustar00rootroot00000000000000#!/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 "party" in result: print("* " + result["person"]["value"] + " ** " + result["party"]["value"]) else: print(result["person"]["value"]) sparqlwrapper-2.0.0/scripts/example.py000066400000000000000000000022041421347431400201110ustar00rootroot00000000000000#!/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-2.0.0/scripts/sparql.py000077500000000000000000000043301421347431400177650ustar00rootroot00000000000000#!/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-2.0.0/setup.cfg000066400000000000000000000037311421347431400162440ustar00rootroot00000000000000[metadata] name = SPARQLWrapper version = attr: SPARQLWrapper.__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 = Ivan Herman, Sergio Fernández, Carlos Tejo Alonso, Alexey Zakhlestin author_email = rdflib-dev@googlegroups.com url = http://rdflib.github.io/sparqlwrapper download_url = https://github.com/RDFLib/sparqlwrapper/releases platforms = any classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: W3C License Operating System :: OS Independent Programming Language :: Python :: 3 Programming Language :: Python :: 3.7 Programming Language :: Python :: 3.8 Programming Language :: Python :: 3.9 Programming Language :: Python :: 3.10 Programming Language :: Python :: Implementation :: CPython Topic :: Software Development :: Libraries :: Python Modules keywords = python sparql rdf rdflib project_urls = Home = https://rdflib.github.io/sparqlwrapper Documentation = https://sparqlwrapper.readthedocs.io Source = https://github.com/RDFLib/sparqlwrapper Tracker = https://github.com/RDFLib/sparqlwrapper/issues [options] packages = SPARQLWrapper install_requires = rdflib>=6.1.1 python_requires = >= 3.7 [options.package_data] SPARQLWrapper = py.typed [options.extras_require] dev = setuptools>=3.7.1 mypy>=0.931 pandas>=1.3.5 pandas-stubs>=1.2.0.48 pandas = pandas>=1.3.5 keepalive = keepalive>=0.5 docs = sphinx < 5 sphinx-rtd-theme [options.entry_points] console_scripts = rqw = SPARQLWrapper.main:main [mypy] files = SPARQLWrapper python_version = 3.7 show_error_codes = True strict = True pretty = True warn_unused_configs = True warn_unused_ignores = True warn_unreachable = True sparqlwrapper-2.0.0/setup.py000066400000000000000000000000461421347431400161310ustar00rootroot00000000000000from setuptools import setup setup() sparqlwrapper-2.0.0/test/000077500000000000000000000000001421347431400153765ustar00rootroot00000000000000sparqlwrapper-2.0.0/test/__init__.py000066400000000000000000000000001421347431400174750ustar00rootroot00000000000000sparqlwrapper-2.0.0/test/test.rq000066400000000000000000000004071421347431400167220ustar00rootroot00000000000000PREFIX dbo: PREFIX rdfs: SELECT DISTINCT ?pllabel WHERE { ?pl a dbo:ProgrammingLanguage; rdfs:label ?pllabel. FILTER(SUBSTR(STR(?pllabel), 1, 1) = "P") } ORDER BY ?pllabel LIMIT 1 sparqlwrapper-2.0.0/test/test_agrovoc-allegrograph_on_hold.py000066400000000000000000000757601421347431400246350ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError logging.basicConfig() endpoint = "https://agrovoc.fao.org/sparql" 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 #### ################ @unittest.expectedFailure # returned type has changed 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().toxml() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # self.assertEqual(type(results), str) 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 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 @unittest.expectedFailure # returned type has changed 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() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # self.assertEqual(type(results), dict) # asking for an unexpected return format for SELECT queryType @unittest.expectedFailure # returned type has changed 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() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # self.assertEqual(type(results), dict) # asking for an unexpected return format for SELECT queryType @unittest.expectedFailure # returned type has changed 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() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # self.assertEqual(type(results), dict) # asking for an unexpected return format for SELECT queryType @unittest.expectedFailure # returned type has changed 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() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # 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() 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() self.assertEqual(type(results), dict) @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), dict) @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), dict) @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), dict) 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 @unittest.expectedFailure # returned type has changed 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() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # self.assertEqual(type(results), dict) # asking for an unexpected return format for ASK queryType @unittest.expectedFailure # returned type has changed 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() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # self.assertEqual(type(results), dict) # asking for an unexpected return format for ASK queryType @unittest.expectedFailure # returned type has changed 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() self.assertEqual(results.__class__.__module__, "xml.dom.minidom") self.assertEqual(results.__class__.__name__, "Document") # self.assertEqual(type(results), dict) # 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() 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() 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 @unittest.expectedFailure # returned type has changed 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) # self.assertEqual(type(results), bytes) # asking for an unexpected return format for CONSTRUCT queryType @unittest.expectedFailure # returned type has changed 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) # 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 application/rdf+xml @unittest.expectedFailure # returned type has changed 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) # 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 application/rdf+xml @unittest.expectedFailure # returned type has changed 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) # 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 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 @unittest.expectedFailure # returned type has changed 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) # self.assertEqual(type(results), bytes) # asking for an unexpected return format for DESCRIBE queryType @unittest.expectedFailure # returned type has changed 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) # 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 application/rdf+xml @unittest.expectedFailure # returned type has changed 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) # 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 application/rdf+xml @unittest.expectedFailure # returned type has changed 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) # 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 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-2.0.0/test/test_allegrograph__v4_14_1__mmi.py000066400000000000000000001640071421347431400237630ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError 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-2.0.0/test/test_blazegraph__wikidata.py000066400000000000000000001721741421347431400231560ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- import inspect import os import sys import time 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError 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-2.0.0/test/test_cli.py000066400000000000000000000456711421347431400175730ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- import inspect import io import os import sys import textwrap 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 from SPARQLWrapper.main import main, parse_args from SPARQLWrapper import POST endpoint = "http://ja.dbpedia.org/sparql" testfile = os.path.join(os.path.dirname(__file__), "test.rq") testquery = "SELECT DISTINCT ?x WHERE { ?x ?y ?z . } LIMIT 1" class SPARQLWrapperCLI_Test_Base(unittest.TestCase): def setUp(self): self.org_stdout, sys.stdout = sys.stdout, io.StringIO() self.org_stderr, sys.stderr = sys.stderr, io.StringIO() def tearDown(self): sys.stdout = self.org_stdout class SPARQLWrapperCLIParser_Test(SPARQLWrapperCLI_Test_Base): def testHelp(self): with self.assertRaises(SystemExit) as cm: parse_args(["-h"]) self.assertEqual(cm.exception.code, 0) self.assertEqual(sys.stdout.getvalue()[:5], "usage") def testVersion(self): with self.assertRaises(SystemExit) as cm: parse_args(["-V"]) self.assertEqual(cm.exception.code, 0) self.assertEqual(sys.stdout.getvalue()[:3], "rqw") def testNoarg(self): with self.assertRaises(SystemExit) as cm: parse_args([]) self.assertEqual(cm.exception.code, 2) self.assertEqual( sys.stderr.getvalue().split("\n")[1], "rqw: error: one of the arguments -f/--file -Q/--query is required", ) def testQueryAndFile(self): with self.assertRaises(SystemExit) as cm: parse_args(["-Q", testquery, "-f", "-"]) self.assertEqual(cm.exception.code, 2) self.assertEqual( sys.stderr.getvalue().split("\n")[1], "rqw: error: argument -f/--file: not allowed with argument -Q/--query", ) def testInvalidFormat(self): with self.assertRaises(SystemExit) as cm: parse_args(["-Q", testquery, "-F", "jjssoonn"]) self.assertEqual(cm.exception.code, 2) self.assertEqual( sys.stderr.getvalue().split("\n")[1], "rqw: error: argument -F/--format: invalid choice: 'jjssoonn' (choose from 'json', 'xml', 'turtle', 'n3', 'rdf', 'rdf+xml', 'csv', 'tsv', 'json-ld')", ) def testInvalidFile(self): with self.assertRaises(SystemExit) as cm: parse_args(["-f", "440044.rq"]) self.assertEqual(cm.exception.code, 2) self.assertEqual( sys.stderr.getvalue().split("\n")[1], "rqw: error: argument -f/--file: file '440044.rq' is not found", ) class SPARQLWrapperCLI_Test(SPARQLWrapperCLI_Test_Base): def testQueryWithEndpoint(self): main( [ "-Q", testquery, "-e", endpoint, ] ) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "link": [], "vars": [ "x" ] }, "results": { "distinct": false, "ordered": true, "bindings": [ { "x": { "type": "uri", "value": "http://www.openlinksw.com/virtrdf-data-formats#default-iid" } } ] } } """ ), ) def testQueryWithFile(self): main(["-f", testfile, "-e", endpoint]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "link": [], "vars": [ "pllabel" ] }, "results": { "distinct": false, "ordered": true, "bindings": [ { "pllabel": { "type": "literal", "xml:lang": "ja", "value": "PARLOG" } } ] } } """ ), ) def testQueryWithFileXML(self): main(["-f", testfile, "-e", endpoint, "-F", "xml"]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ PARLOG """ ), ) def testQueryWithFileTurtle(self): main(["-f", testfile, "-e", endpoint, "-F", "turtle"]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ @prefix res: . @prefix rdf: . _:_ a res:ResultSet . _:_ res:resultVariable "pllabel" . _:_ res:solution [ res:binding [ res:variable "pllabel" ; res:value "PARLOG"@ja ] ] .\n """ ), ) def testQueryWithFileTurtleQuiet(self): main( [ "-f", testfile, "-e", endpoint, "-F", "turtle", "-q", ] ) self.assertEqual(sys.stderr.getvalue(), "") self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ @prefix res: . @prefix rdf: . _:_ a res:ResultSet . _:_ res:resultVariable "pllabel" . _:_ res:solution [ res:binding [ res:variable "pllabel" ; res:value "PARLOG"@ja ] ] .\n """ ), ) def testQueryWithFileN3(self): main(["-f", testfile, "-e", endpoint, "-F", "n3"]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ @prefix res: . @prefix rdf: . _:_ a res:ResultSet . _:_ res:resultVariable "pllabel" . _:_ res:solution [ res:binding [ res:variable "pllabel" ; res:value "PARLOG"@ja ] ] .\n """ ), ) def testQueryRDF(self): main(["-Q", "DESCRIBE ", "-e", endpoint, "-F", "rdf"]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ @prefix dc: . @prefix foaf: . foaf:isPrimaryTopicOf . a foaf:Document ; dc:language "ja" ; foaf:primaryTopic . """ ), ) def testQueryWithFileRDFXML(self): main(["-f", testfile, "-e", endpoint, "-F", "rdf+xml"]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ PARLOG """ ), ) def testQueryWithFileCSV(self): main(["-f", testfile, "-e", endpoint, "-F", "csv"]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ "pllabel" "PARLOG"\n """ ), ) def testQueryWithFileTSV(self): main(["-f", testfile, "-e", endpoint, "-F", "tsv"]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ "pllabel" "PARLOG"\n """ ), ) def testQueryToLovFuseki(self): main(["-e", "https://lov.linkeddata.es/dataset/lov/sparql/", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "http://www.w3.org/2002/07/owl#someValuesFrom" } } ] } } """ ), ) def testQueryToRDF4J(self): main( [ "-e", "http://vocabs.ands.org.au/repository/api/sparql/csiro_international-chronostratigraphic-chart_2018-revised-corrected", "-Q", testquery, ] ) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" } } ] } } """ ), ) def testQueryToAllegroGraph(self): main(["-e", "https://mmisw.org/sparql", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "https://mmisw.org/ont/~mjuckes/cmip_variables_alpha/rsdcs4co2" } } ] } } """ ), ) def testQueryToGraphDBEnterprise(self): main(["-e", "http://factforge.net/repositories/ff-news", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" } } ] } } """ ), ) def testQueryToStardog(self): main(["-e", "https://lindas.admin.ch/query", "-Q", testquery, "-m", POST]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "http://classifications.data.admin.ch/canton/bl" } } ] } } """ ), ) def testQueryToAgrovoc_AllegroGraph(self): main(["-e", "https://agrovoc.fao.org/sparql", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "http://aims.fao.org/aos/agrovoc/" } } ] } } """ ), ) def testQueryToVirtuosoV8(self): main(["-e", "http://dbpedia-live.openlinksw.com/sparql", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "link": [], "vars": [ "x" ] }, "results": { "distinct": false, "ordered": true, "bindings": [ { "x": { "type": "uri", "value": "http://www.openlinksw.com/virtrdf-data-formats#default-iid" } } ] } } """ ), ) def testQueryToVirtuosoV7(self): main(["-e", "http://dbpedia.org/sparql", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "link": [], "vars": [ "x" ] }, "results": { "distinct": false, "ordered": true, "bindings": [ { "x": { "type": "uri", "value": "http://www.openlinksw.com/virtrdf-data-formats#default-iid" } } ] } } """ ), ) def testQueryToBrazeGraph(self): main(["-e", "https://query.wikidata.org/sparql", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "http://wikiba.se/ontology#Dump" } } ] } } """ ), ) def testQueryToFuseki2V3_6(self): main(["-e", "https://agrovoc.uniroma2.it/sparql/", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "http://aims.fao.org/aos/agrovoc/" } } ] } } """ ), ) def testQueryToFuseki2V3_8(self): main(["-e", "http://zbw.eu/beta/sparql/stw/query", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "uri", "value": "http://www.w3.org/2004/02/skos/core" } } ] } } """ ), ) def testQueryTo4store(self): main(["-e", "http://rdf.chise.org/sparql", "-Q", testquery]) self.assertEqual( sys.stdout.getvalue(), textwrap.dedent( """\ { "head": { "vars": [ "x" ] }, "results": { "bindings": [ { "x": { "type": "bnode", "value": "b1f4d352f000000fc" } } ] } } """ ), ) sparqlwrapper-2.0.0/test/test_fuseki2__v3_6_0__agrovoc.py000066400000000000000000001602761421347431400234650ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError logging.basicConfig() endpoint = "https://agrovoc.uniroma2.it/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-2.0.0/test/test_fuseki2__v3_8_0__stw.py000066400000000000000000001604321421347431400226360ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- import inspect import os import sys import time 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError 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-2.0.0/test/test_graphdbEnterprise__v8_9_0__rs.py000066400000000000000000001654121421347431400245560ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError logging.basicConfig() # http://factforge.net/ # human UI http://rs.ontotext.com/sparql endpoint = "http://factforge.net/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-2.0.0/test/test_lov-fuseki_on_hold.py000066400000000000000000001767221421347431400226140ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError 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-2.0.0/test/test_rdf4j__geosciml.py000066400000000000000000001675111421347431400220540ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError 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-2.0.0/test/test_stardog__lindas.py000066400000000000000000001670341421347431400221560ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError logging.basicConfig() # human UI https://lindas.admin.ch/sparql/ endpoint = "https://lindas.admin.ch/query" 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-2.0.0/test/test_store__v1_1_4.py000066400000000000000000002006531421347431400213610ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError logging.basicConfig() endpoint = "http://rdf.chise.org/sparql" # 4store SPARQL server v1.1.4 prefixes = """ PREFIX rdf: PREFIX rdfs: PREFIX skos: """ selectQuery = """ SELECT DISTINCT ?s WHERE { ?s a ?o . } LIMIT 100 """ selectQueryCSV_TSV = """ SELECT DISTINCT ?s ?o WHERE { ?s a ?o . } LIMIT 100 """ askQuery = """ ASK { ?type a . } """ constructQuery = """ CONSTRUCT { _:v rdfs:type ?type . _:v rdfs:comment "this is only a mock node to test library" . } WHERE { rdfs:type ?type . } """ describeQuery = """ DESCRIBE """ queryBadFormed = """ PREFIX xsd: WHERE { ?x "214"^^xsd:integer . } SELECT ?x """ 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: PREFIX rdfs: SELECT ?char ?sound WHERE { ?char ?sound . } ORDER BY ?sound 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 ): # 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 #### ################ @unittest.expectedFailure # HTTP Error 502: Bad Gateway 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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) @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 502: Bad Gateway 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 502: Bad Gateway 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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) @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 502: Bad Gateway 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 502: Bad Gateway 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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) @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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) @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 502: Bad Gateway 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 502: Bad Gateway 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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.expectedFailure # HTTP Error 500: SPARQL protocol error 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) @unittest.skip( "4store does not support receiving unexpected output values (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 ('text' is the one used) @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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) @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.skip( "4store does not support receiving unexpected output values (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) @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 502: Bad Gateway 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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 @unittest.expectedFailure # HTTP Error 500: SPARQL protocol error 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-2.0.0/test/test_virtuoso__v7_20_3230__dbpedia.py000066400000000000000000002037171421347431400242450ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError logging.basicConfig() endpoint = "https://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") @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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-2.0.0/test/test_virtuoso__v8_03_3313__dbpedia.py000066400000000000000000002042171421347431400242450ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- 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 ( CSV, GET, JSON, JSONLD, N3, POST, RDF, RDFXML, TSV, TURTLE, XML, SPARQLWrapper, ) from SPARQLWrapper.SPARQLExceptions import QueryBadFormed from SPARQLWrapper.Wrapper import ( _CSV, _RDF_JSONLD, _RDF_N3, _RDF_TURTLE, _RDF_XML, _SPARQL_JSON, _SPARQL_XML, _TSV, _XML, ) _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 import logging from urllib.error import HTTPError logging.basicConfig() endpoint = "https://live.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") @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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 @unittest.skip("Virtuoso refuse POST") 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) @unittest.skip("Virtuoso refuse POST") 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("Virtuoso refuse POST") 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-2.0.0/test/test_wrapper.py000066400000000000000000001126221421347431400204730ustar00rootroot00000000000000#!/usr/bin/python # -*- coding: utf-8 -*- import inspect import logging import os import sys import time import unittest import urllib.error import urllib.parse import urllib.request from urllib.parse import parse_qs, parse_qsl, urlparse from urllib.request import Request 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 import warnings from io import StringIO # we don't want to let Wrapper do real web-requests. so, we are… # constructing a simple Mock! from urllib.error import HTTPError warnings.simplefilter("always") import SPARQLWrapper.Wrapper as _victim from SPARQLWrapper import ( BASIC, CSV, DIGEST, GET, INSERT, JSON, JSONLD, N3, POST, POSTDIRECTLY, RDF, RDFXML, SELECT, TSV, TURTLE, URLENCODED, XML, SPARQLWrapper, ) from SPARQLWrapper.Wrapper import ( EndPointInternalError, EndPointNotFound, QueryBadFormed, QueryResult, 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("")) return urlopener_error def urlopener_check_data_encoding(request): if isinstance(request.data, str): raise TypeError # DONE class SPARQLWrapper_Test(unittest.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: 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) result = {} for k, vs in parameters.items(): result[k] = [v.encode("utf-8") for v in vs] return result @classmethod def setUpClass(cls): urllib.request._opener = None # clear value. Due to the order of test execution, the value of urllib.request._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") # Ignore format 'nonexistent format'; current instance supports: ... 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) self.wrapper.setReturnFormat(JSONLD) self.assertEqual(JSONLD, self.wrapper.query().requestedFormat) 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")) self.assertTrue(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(urllib.request._opener) self.wrapper.setHTTPAuth(DIGEST) self.assertIsNone(urllib.request._opener) request = self._get_request(self.wrapper) self.assertFalse(request.has_header("Authorization")) self.assertEqual(self.wrapper.http_auth, DIGEST) self.assertIsInstance(urllib.request._opener, urllib.request.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 = '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.assertEqual(query_bytes, request.data) self.wrapper.setQuery(query_bytes) request = self._get_request(self.wrapper) self.assertEqual(query_bytes, request.data) self.wrapper.setRequestMethod(URLENCODED) self.wrapper.setQuery(query) parameters = self._get_request_parameters_as_bytes(self.wrapper) self.assertEqual(query_bytes, parameters["update"][0]) self.wrapper.setQuery(query_bytes) parameters = self._get_request_parameters_as_bytes(self.wrapper) self.assertEqual(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.assertEqual(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.assertEqual(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.assertEqual(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.assertEqual(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.assertEqual(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.assertEqual(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__() next(qr) 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 # if len(w) > 0: print(w[0].message) # FOR DEBUG # if len(w) > 1: print(w[1].message) # FOR DEBUG 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/json", JSON)) self.assertEqual(0, _mime_vs_type("application/ld+json", JSONLD)) self.assertEqual(0, _mime_vs_type("application/rdf+xml", XML)) self.assertEqual(0, _mime_vs_type("application/rdf+xml", RDF)) self.assertEqual(0, _mime_vs_type("application/rdf+xml", RDFXML)) 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)) # unknown response content type 'application/x-foo-bar' returning raw response... self.assertEqual(1, _mime_vs_type("application/x-foo-bar", XML), "invalid mime") # Format requested was xxx, but yyy (zzz) has been returned by the endpoint 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)) # Format requested was xxx, but yyy (zzz) has been returned by the endpoint 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 # if len(w) > 1: print(w[1].message) # FOR DEBUG 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")) # Format return was xxx, but yyy was expected. No printing. 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")) # Unknown response content type. Returning raw content-type ('application/x-foo-bar'). # Format return was application/x-foo-bar, but JSON was expected. No printing. 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-2.0.0/tox.ini000066400000000000000000000002731421347431400157340ustar00rootroot00000000000000[tox] envlist = py37, py38, py39, py310 [testenv] # run the tests # ``{posargs}`` will be substituted with positional arguments from command line commands = python -m unittest {posargs}